Algorithm for sublist in python

Hi All,

I have and issue creating sub-lists in python. Here is my original list:

and I want to get the first and last index of every sublist, acording the indices from the original list. Here’s an image to illustrate this:

This is a part a python code. I’m not working with OOTB nodes.

Thanks in advance!

Hi Jorge,

Try to append the values in a list inside the loop. (I took this example from an old post on this forum).
image

Or something like this:

image

1 Like

There’s probably a cleaner way of doing this but a simple use of append will work.

import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
clr.AddReference('DSCoreNodes')
from DSCore import *
#The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN
items = IN[0]
inlist = IN[1]
newlist = []

for indices in inlist:
	sublist = []
	for i in indices:
		sublist.append(items[i])
	newlist.append(sublist)

#Assign your output to the OUT variable.
OUT = newlist
1 Like

Thanks both @Nick_Boyts and @Giovanni_Brogiolo for the response. I’m creating list using append, but I’m looking a bit further. I can’t manage to get the algorith to do the task mentioned above.

I could get the indices from the “existe” and “no existe” elements, but I need to get the indices in the same list.

image

image

inic_tramo =[]
for i in range(len(tras_arriba)):
    aux = []
    for j in range(len(tras_arriba[i])):
        if tras_arriba[i][j] == 'existe':
            aux.append(j)
        else:
            j = j+1
    inic_tramo.append(aux)

fin_tramo = []
for i in range(len(tras_arriba)):
    aux = []
    for j in range(len(tras_arriba[i])):
        if tras_arriba[i][j] == 'no existe':
            aux.append(j)
        else:
            pass
    fin_tramo.append(aux)

OUT = (inic_tramo,fin_tramo)

OK, I think I understand now. So your sublist of indices will be the first “existe” and the first “no existe” the list encounters, then you begin a new sublist doing the same thing. Should be doable. I’ll play around with it.

1 Like

Exactly!

Is your end goal to get the indices or to convert your list into sublists based on those indices?

The goal is to get the indices, so I was thinking of a sublist containing the first and the last item of every sequence “existe, existe…,no existe”.

If there is a sequence with only a “no existe”, this sublist contains only one item.Like the case of the elements 7,8 and 11 from the original list.

nailed it!

resultado = []
for i in range(len(tras_arriba)):
    aux = []
    resp = []
    for j in range(0,len(tras_arriba[i])):
        if tras_arriba[i][j] == 'existe':
            aux.append(j)
        else:
            aux.append(j)
            resp.append(aux)
            aux = []

    resultado.append(resp)

1 Like