How to access a field of a namedtuple using a vari

2019-02-11 14:32发布

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条回答
我想做一个坏孩纸
2楼-- · 2019-02-11 15:00

You can use getattr

getattr(my_car, field)
查看更多
登录 后发表回答