遍历 python 中命名元组的元素
Looping over elements of named tuple in python
我有一个命名元组,我像这样为其赋值:
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))
有没有办法遍历命名元组的元素?我试过这样做,但不起作用:
for fld in self.CFTs._fields:
self.CFTs.fld= numpy.zeros(shape=(self.yshape, self.xshape))
namedtuple 是一个元组,因此您可以像普通元组一样进行迭代:
>>> from collections import namedtuple
>>> A = namedtuple('A', ['a', 'b'])
>>> for i in A(1,2):
print i
1
2
但是元组是不可变的,因此您不能更改值
如果您需要字段的名称,您可以使用:
>>> 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)
输出:
x 1
y 2
Python 3.6+
您可以像普通元组一样简单地遍历项目:
MyNamedtuple = namedtuple("MyNamedtuple", "a b")
a_namedtuple = MyNamedtuple(a=1, b=2)
for i in a_namedtuple:
print(i)
从Python 3.6开始,如果你需要属性名字,你现在需要做的是:
for name, value in a_namedtuple._asdict().items()
print(name, value)
备注
如果您尝试使用 a_namedtuple._asdict().iteritems()
,它将抛出 AttributeError: 'collections.OrderedDict' object has no attribute 'iteritems'
我有一个命名元组,我像这样为其赋值:
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))
有没有办法遍历命名元组的元素?我试过这样做,但不起作用:
for fld in self.CFTs._fields:
self.CFTs.fld= numpy.zeros(shape=(self.yshape, self.xshape))
namedtuple 是一个元组,因此您可以像普通元组一样进行迭代:
>>> from collections import namedtuple
>>> A = namedtuple('A', ['a', 'b'])
>>> for i in A(1,2):
print i
1
2
但是元组是不可变的,因此您不能更改值
如果您需要字段的名称,您可以使用:
>>> 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)
输出:
x 1
y 2
Python 3.6+
您可以像普通元组一样简单地遍历项目:
MyNamedtuple = namedtuple("MyNamedtuple", "a b")
a_namedtuple = MyNamedtuple(a=1, b=2)
for i in a_namedtuple:
print(i)
从Python 3.6开始,如果你需要属性名字,你现在需要做的是:
for name, value in a_namedtuple._asdict().items()
print(name, value)
备注
如果您尝试使用 a_namedtuple._asdict().iteritems()
,它将抛出 AttributeError: 'collections.OrderedDict' object has no attribute 'iteritems'