我有一个带集合的模块:
import collections
named_tuple_sex = collections.namedtuple(
'FlightsResultsSorter',
['TotalPriceASC',
'TransfersASC',
'FlightTimeASC',
'DepartureTimeASC',
'DepartureTimeDESC',
'ArrivalTimeASC',
'ArrivalTimeDESC',
'Airlines']
)
FlightsResultsSorter = named_tuple_sex(
FlightsResultsSorter('TotalPrice', SortOrder.ASC),
FlightsResultsSorter('Transfers', SortOrder.ASC),
FlightsResultsSorter('FlightTime', SortOrder.ASC),
FlightsResultsSorter('DepartureTime', SortOrder.ASC),
FlightsResultsSorter('DepartureTime', SortOrder.DESC),
FlightsResultsSorter('ArrivalTime', SortOrder.ASC),
FlightsResultsSorter('ArrivalTime', SortOrder.DESC),
FlightsResultsSorter('Airlines', SortOrder.ASC)
)
在另一个模块中,我按照这个集合进行迭代,我希望获得项目的名称:
for x in FlightsResultsSorter:
self.sort(x)
所以在代码中我想要代替x(对象)传递例如“DepartureTimeASC”或“ArrivalTimeASC”。
我怎样才能得到这个名字?
祝你好运
答案 0 :(得分:63)
如果您尝试获取实际名称,请使用_fields
属性:
In [50]: point = collections.namedtuple('point', 'x, y')
In [51]: p = point(x=1, y=2)
In [52]: for name in p._fields:
....: print name, getattr(p, name)
....:
x 1
y 2
答案 1 :(得分:28)
from itertools import izip
for x, field in izip(FlightsResultsSorter, named_tuple_sex._fields):
print x, field
您也可以使用FlightsResultsSorter._asdict()
来获取字典。