How to access a field of a namedtuple using a variable for the field name?

后端 未结 4 2010
忘掉有多难
忘掉有多难 2020-12-28 11:19

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

from collections import namedtuple
Car = namedtuple(\'Car\', \'color mileage\')
my_car = Car(\'         


        
4条回答
  •  粉色の甜心
    2020-12-28 12:14

    Another way of accessing them can be:

    field_idx = my_car._fields.index(field)
    my_car[field_idx]
    

    Extract index of the field and then use it to index the namedtuple.

提交回复
热议问题