-6
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())
4

4 回答 4

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]}
于 2012-12-12T18:08:54.187 回答
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'而不是字符串"'png'"等),你需要知道它们所用的语言并解析它。看起来它们是 Python 的一个子集,其中每一件事都是没有转义的单引号字符串文字、非指数格式的浮点文字或布尔文字,但我不会在不知道的情况下假设值来自哪里(我当然不会eval在不知道它们来自哪里的情况下直接调用它们,因为这样有人可以只保留os.system('rm -rf /')文本文件,然后您会对其进行评估。

于 2012-12-12T18:08:08.117 回答
0
write1 = {'write1':[1,2,3,4] }

应该管用 ...

于 2012-12-12T18:03:06.367 回答
0

使用默认值作为列表创建一个 defaultdict,然后开始附加(或使用其他列表方法)。

于 2012-12-12T18:03:31.057 回答