【问题标题】:Looping over elements of named tuple in python在python中循环命名元组的元素
【发布时间】:2016-03-03 05:55:06
【问题描述】:

我有一个命名元组,我给它赋值:

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))

【问题讨论】:

    标签: python namedtuple


    【解决方案1】:

    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
    

    【讨论】:

    • 感谢@Pawel,关于不变性的要点。有什么方法可以根据我的特定代码调整您的响应?
    • 只需将 a 替换为 self.CTFs
    • 这似乎在 Python 3.6 中有效:a._asdict().items()
    • @ThorSummoner _asdict 是一个函数,而不是一个属性。你能删除你的评论吗?这是误导。
    • .iteritems() -> .items() for python3
    【解决方案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
    

    【讨论】:

      【解决方案3】:

      您可以像普通元组一样简单地遍历项目:

      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'

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多