Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over elements of named tuple in python

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)) 
like image 651
user308827 Avatar asked Nov 29 '15 15:11

user308827


People also ask

How do you loop a list over a tuple in Python?

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!

Can you loop over a tuple?

You can loop through the tuple items by using a for loop.

Can we loop tuple in Python?

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.

Are Named tuples iterable?

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.


2 Answers

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 
like image 52
Paweł Kordowski Avatar answered Sep 20 '22 22:09

Paweł Kordowski


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 
like image 22
Jano Avatar answered Sep 18 '22 22:09

Jano