[英]Processing multidimensional lists with nested for loops in python?
我正在为Nuke-The Foundry编写代码。.我已经敲了三个小时了..在Google上查找但没有成功,我要尝试的工作基本上是创建二维列表并在其中填充一些内容。我的情况下,我想用db = [['nodeName1', 'inputnName1'], ['nodeName2', 'imputName2'], etc...]
填充列表db = [['nodeName1', 'inputnName1'], ['nodeName2', 'imputName2'], etc...]
我用db = [[None for x in range(2)] for y in range (nMasks)]
创建列表-其中nMasks是“ db”中应有多少行的变量
现在我想以某种方式用我的变量填充列表。
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
这给了我想要的结果不同-当我这样做时:
print db[0][0]['name'].value()
print db[0][1]
print db[1][0]['name'].value()
print db[1][1]
我得到结果:
节点1 a节点1 a
我希望它看起来像:
节点1 a节点2 a
注意:也许对此有更优雅的解决方案?
我通常通过将值附加到列表中来填充列表。 这样,您无需事先知道列表的大小。 您似乎想要从所需的输出中执行的操作是将selectedNodes
放入2D数组db
。 似乎db[i][0]
应该是nuke.selectedNodes()[i]
而db[i][1]
应该是字符串。 我不太了解您的nMasks
与所选节点的数量有什么关系,但是,如果您打算获取所有所选节点,那么以下似乎更自然的获取您想要的2D列表
sn = nuke.selectedNodes()
db =
for n in nuke.selectedNodes():
db.append([n,'a'])
获得相同列表的方法有很多。 例如,您可以使用列表推导将其汇总为一行
db = [[n,'a'] for n in nuke.selectedNodes()]
但是,如果您想在问题的代码中使用嵌套循环,可以这样做
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.