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))
Use the enumerate() function to iterate over a list of tuples, e.g. for index, tup in enumerate(my_list): . The enumerate function returns an object that contains tuples where the first item is the index, and the second is the value. Copied!
You can loop through the tuple items by using a for loop.
You can loop through the list items by using a while loop. Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by refering to their indexes. Remember to increase the index by 1 after each iteration.
Since namedtuple is iterable you can use the iterable methods. For example, if you have "coords" as a class instance, you cannot look for what is the max coord.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With