我有以下清单
a = [[a1, b1, c1, [d1, e1, f1],
[a2, b2, c2, [d2, e2, f2],
[a3, b3, c3, [d3, e3, f3]]
Run Code Online (Sandbox Code Playgroud)
我怎样才能将它变成一个命名元组列表
a[0].val1
>>> a1
a[1].val2
>>> b2
a[0].box
>>> [d1, e1, f1]
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 11
使用collections.namedtuple类工厂创建一个命名的元组类:
mynamedtuple = collections.namedtuple('mynamedtuple', ('val1', 'val2', 'val3', 'box'))
somenamedtuple = mynamedtuple('a1', 'a2', 'a3', ['d1', 'e1', 'f1'])
somenamedtuple.box # returns ['d1', 'e1', 'f1']
Run Code Online (Sandbox Code Playgroud)
您可以使用列表解析转换现有列表:
a = [mynamedtuple(*el) for el in a]
Run Code Online (Sandbox Code Playgroud)