Looping elements of a named tuple in python

I have a named tuple that assigns values ​​as follows:

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 iterate over elements named tuple? I tried to do this, but not working:

 for fld in self.CFTs._fields: self.CFTs.fld= numpy.zeros(shape=(self.yshape, self.xshape)) 
+8
python namedtuple
source share
1 answer

namedtuple is a tuple, so you can iterate over a regular 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 a field name 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 
+7
source share

All Articles