Processing multidimensional lists with nested for loops in python?

638 views Asked by At

I am writing code for Nuke - The foundry.. I have been banging my head for 3 hours now.. looking up on google but without success What i am trying to do is basically create 2 dimensional list and populate it with something.. In my case i want to populate the list with db = [['nodeName1', 'inputnName1'], ['nodeName2', 'imputName2'], etc...]

I create the list with db = [[None for x in range(2)] for y in range (nMasks)] - where nMasks is a variable of how many rows there should be in "db"

now i want to populate the list with my variables somehow.. i tried this:

for i in range(len(db)): #row
    for j in range(len(db[i])): #element
        for n in nuke.selectedNodes():
            if j == 0:
                db[i][j] = n #populate list with node
            if j != 0:
                db[i][j] = 'a' #for now it's just an a and nothing more but ill have to change this to an actual nodeName 

This gives me different result of what i want - when i do:

print db[0][0]['name'].value()
print db[0][1]

print db[1][0]['name'].value()
print db[1][1]

i get result:

Result:

Node1 a Node1 a

and i want it to look like:

Result:

Node1 a Node2 a

note: maybe there is even more elegant solution for this?

1

There are 1 answers

1
lucianopaz On BEST ANSWER

I normally populate a list by appending values to it. This way you don't need to know in advance the size of the list. What it seems that you are trying to do from your desired output, is to get the selectedNodes into a 2D array db. It seems like db[i][0] should be be nuke.selectedNodes()[i] while db[i][1] should be a string. I don't really understand what your nMasks has to do with the number of selected nodes but, if your intention was to get all the selected nodes, it seems that the following would be more natural to get the 2D list that you want

sn = nuke.selectedNodes()
db = 
for n in nuke.selectedNodes():
    db.append([n,'a'])

edit

There are many, many ways to get the same list. For instance, you could use list comprehension to sum it up into a single line

db = [[n,'a'] for n in nuke.selectedNodes()]

But if you want to use nested loops like in your question's code, you could do it like this

db = [[None for x in range(2)] for y in range (nMasks)]
for i in range(len(db)):
    for j in range(len(db[0])):
        if j == 0:
            db[i][j] = nuke.selectedNodes()[i] #populate list with node
        else:
            db[i][j] = 'a'