Looping over elements of named tuple in python

2020-06-30 05:20发布

问题:

I have a named tuple which I assign values to like this:

class test(object):
            self.CFTs = collections.namedtuple('CFTs', 'c4annual c4perren c3perren ntfixing')

            self.CFTs.c4annual = numpy.zeros(shape=(self.yshape, self.xshape))
            self.CFTs.c4perren = numpy.zeros(shape=(self.yshape, self.xshape))
            self.CFTs.c3perren = numpy.zeros(shape=(self.yshape, self.xshape))
            self.CFTs.ntfixing = numpy.zeros(shape=(self.yshape, self.xshape))

Is there a way to loop over elements of named tuple? I tried doing this, but does not work:

for fld in self.CFTs._fields:
                self.CFTs.fld= numpy.zeros(shape=(self.yshape, self.xshape))

回答1:

namedtuple is a tuple so you can iterate as over normal tuple:

>>> from collections import namedtuple
>>> A = namedtuple('A', ['a', 'b'])
>>> for i in A(1,2):
    print i


1
2

but tuples are immutable so you cannot change the value

if you need the name of the field you can use:

>>> a = A(1, 2)
>>> for name, value in a._asdict().iteritems():
    print name
    print value


a
1
b
2

>>> for fld in a._fields:
    print fld
    print getattr(a, fld)


a
1
b
2


回答2:

from collections import namedtuple
point = namedtuple('Point', ['x', 'y'])(1,2)
for k, v in zip(point._fields, point):
    print(k, v)

Output:

x 1
y 2