【问题标题】:How come Python's dict doesn't have .iter()?为什么 Python 的 dict 没有 .iter()?
【发布时间】:2011-07-15 11:25:05
【问题描述】:
def complicated_dot(v, w):
        dot = 0
        for (v_i, w_i) in zip(v, w):
            for x in v_i.iter():
                if x in w_i:
                    dot += v_i[x] + w_i[x]
        return float(dot)

我收到一条错误消息:

AttributeError: 'dict' object has no attribute 'iter'

【问题讨论】:

  • 不要按照@yi_H 的建议直接使用__iter__。使用iter(v_i) 或仅使用for x in v_i
  • 呃我不想建议使用它,只是告诉它的名字。实际上这两个代码都会调用__iter__

标签: python


【解决方案1】:

考虑以下dict

>>> d
{'a': 1, 'c': 3, 'b': 2}

您可以像这样遍历键:

>>> for k in d:
...     print(k, d[k])
... 
('a', 1)
('c', 3)
('b', 2)

这隐式调用了特殊方法__iter__(),但请记住:

Explicit is better than implicit.

Python 2.x

您希望以下返回什么?

>>> tuple(d.iter())

也许太模棱两可了?

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'iter'

这似乎是一个非常合理的方法。

如果您只想迭代 keys 怎么办?

>>> tuple(d.iterkeys())
('a', 'c', 'b')

不错!以及价值观

>>> tuple(d.itervalues())
(1, 3, 2)

键和值如何成对(元组)?

>>> tuple(d.iteritems())
(('a', 1), ('c', 3), ('b', 2))

Python 3.x

事物是slightly differentdict.keys()dict.values()dict.items()返回的对象是view objects。不过,它们的使用方式几乎相同:

>>> tuple(d.keys())
('a', 'c', 'b')
>>> tuple(d.values())
(1, 3, 2)
>>> tuple(d.items())
(('a', 1), ('c', 3), ('b', 2))

【讨论】:

    【解决方案2】:

    It has iter。但是你可以写

    for x in v_i:
    

    【讨论】:

      【解决方案3】:
      v_i.itervalues()
      

      您有iterkeysiteritemsitervalues。选择一个。

      【讨论】:

        猜你喜欢
        • 2017-03-30
        • 1970-01-01
        • 2011-11-08
        • 1970-01-01
        • 2018-04-30
        • 2020-02-22
        • 1970-01-01
        • 1970-01-01
        • 2018-01-14
        相关资源
        最近更新 更多