How to access a field of a namedtuple using a vari

2019-02-11 14:52发布

问题:

I can access elements of a named tuple by name as follows(*):

from collections import namedtuple
Car = namedtuple('Car', 'color mileage')
my_car = Car('red', 100)
print my_car.color

But how can I use a variable to specify the name of the field I want to access? E.g.

field = 'color'
my_car[field] # doesn't work
my_car.field # doesn't work

My actual use case is that I'm iterating through a pandas dataframe with for row in data.itertuples(). I am doing an operation on the value from a particular column, and I want to be able to specify the column to use by name as a parameter to the method containing this loop.

(*) example taken from here. I am using Python 2.7.

回答1:

You can use getattr

getattr(my_car, field)