如何将元组转换为namedtuple?

时间:2014-07-28 16:48:56

标签: python python-3.x namedtuple

我想在内部使用namedtuples,但我希望保持与那些为我提供普通元组的用户的兼容性。

from collections import namedtuple

tuplePi=(1,3.14,"pi") #Normal tuple 

Record=namedtuple("MyNamedTuple", ["ID", "Value", "Name"])

namedE=Record(2, 2.79, "e") #Named tuple

namedPi=Record(tuplePi) #Error
TypeError: __new__() missing 2 required positional arguments: 'Value' and 'Name'

tuplePi.__class__=Record
TypeError: __class__ assignment: only for heap types

1 个答案:

答案 0 :(得分:41)

您可以使用*args调用语法:

namedPi = Record(*tuplePi)

这将tuplePi序列的每个元素作为单独的参数传递。

您还可以使用namedtuple._make() class method将任何序列转换为实例:

namedPi = Record._make(tuplePi)

演示:

>>> from collections import namedtuple
>>> Record = namedtuple("MyNamedTuple", ["ID", "Value", "Name"])
>>> tuplePi = (1, 3.14, "pi")
>>> Record(*tuplePi)
MyNamedTuple(ID=1, Value=3.14, Name='pi')
>>> Record._make(tuplePi)
MyNamedTuple(ID=1, Value=3.14, Name='pi')