简体   繁体   中英

Getting name of value from namedtuple

I have a module with collection:

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)
)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM