Write1 [1.0]
Write1 [12.0]
Write1 ['C:/Users/san/Modeler/']
Write1 ['png']
Write1 ['rgb']
Write1 [True]
Write2 [1.0]
Write2 [1.0]
Write2 ['']
Write2 [' ']
Write2 ['rgb']
Write2 [False]
我想像这样制作词典 {'Write1':[1.0,12.0,'c:/ path','png','rgb',True],'Write2':[1.0,1.0,'','','rgb',False]} 列表中的值来自nuke.toNode(wNode)[eachAttrib] .value() 这就是我试图做的事情
attributes=[]
wnodeData={}
for wNode in writeNodes:
for eachAttrib in ['first','last','file','file_type','channels','use_limit']:
wnodeData[wNode]=attributes
attributes.append(nuke.toNode(wNode)[eachAttrib].value())
答案 0 :(得分:2)
类似的东西:
text="""Write1 [1.0]
Write1 [12.0]
Write1 ['C:/Users/san/Modeler/']
Write1 ['png']
Write1 ['rgb']
Write1 [True]
Write2 [1.0]
Write2 [1.0]
Write2 ['']
Write2 [' ']
Write2 ['rgb']
Write2 [False]"""
from ast import literal_eval
d = {}
lines = text.splitlines()
for line in lines:
k, v = line.split(' ', 1)
val = literal_eval(v)[0]
d.setdefault(k, []).append(val)
print d
# {'Write1': [1.0, 12.0, 'C:/Users/san/Modeler/', 'png', 'rgb', True], 'Write2': [1.0, 1.0, '', ' ', 'rgb', False]}
答案 1 :(得分:1)
import collections
s = '''Write1 [1.0]
Write1 [12.0]
Write1 ['C:/Users/san/Modeler/']
Write1 ['png']
Write1 ['rgb']
Write1 [True]
Write2 [1.0]
Write2 [1.0]
Write2 ['']
Write2 [' ']
Write2 ['rgb']
Write2 [False]'''
d = collections.defaultdict(list)
for line in s.split('\n'):
print(line)
key, val = line.split(' ', 1)
d[key].append(val[1:-1])
print(d)
显然,如果你有一个文本文件而不是一个字符串,你可以替换for循环,比如说:
with open('mystuff.txt', 'r') as f:
for line in f:
如果你想实际评估括号内的值(所以你得到1.0
而不是字符串'1.0'
的浮点数,字符串'png'
而不是字符串{{ 1}}等等,你需要知道他们写的语言并解析它。看起来它们是Python的一个子集,其中每个东西都是没有转义的单引号字符串文字,非指数格式的浮点文字或布尔文字,但我不会假设不知道价值来自哪里(我当然不会在不知道它们来自何处的情况下调用"'png'"
,因为那时有人可以将eval
粘贴在文本文件中,并且你会评估
答案 2 :(得分:0)
write1 = {'write1':[1,2,3,4] }
应该有用......
答案 3 :(得分:0)
使用默认值作为列表创建一个defaultdict,然后开始追加(或使用其他列表方法)。