开发者

Getting name of value from namedtuple

I have a module with collection:

import collections
named_tuple_sex = collections.namedtuple(
                    'FlightsResultsSorter',
                        ['To开发者_C百科talPriceASC',
                         '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)
)

and in another module, I iterate by this collection and I want to get the name of the item:

for x in FlightsResultsSorter:
            self.sort(x)

so in the code above, I want instead of x (which is an object) to pass, for example, DepartureTimeASC or ArrivalTimeASC.

How can I get this name?


If you're trying to get the actual names, use the _fields attribute:

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


from itertools import izip

for x, field in izip(FlightsResultsSorter, named_tuple_sex._fields):
    print x, field

You can also use FlightsResultsSorter._asdict() to get a dict.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜