【问题标题】:Is some_dict.items() an iterator in Python?some_dict.items() 是 Python 中的迭代器吗?
【发布时间】:2019-02-07 15:51:07
【问题描述】:

我对迭代器和可迭代对象之间的区别有点困惑。我读了很多书,得到了这么多:

迭代器:在其类中具有__next__ 的对象。你可以调用 next() 。所有迭代器都是可迭代的。

Iterable:在其类中定义__iter____getitem__ 的对象。如果可以使用 iter() 构建迭代器,那么它就是可迭代的。并非所有可迭代对象都是迭代器。

some_dict.items() 是迭代器吗?我知道some_dict.iteritems() 会在 Python2 中,对吧?

我只是在检查,因为我正在做的一门课程说它是,而且我很确定它只是一个可迭代的(不是迭代器)。

感谢您的帮助:)

【问题讨论】:

  • @ytu 并不是真正的重复 IMO,无论如何,接受的答案不正确解决了这个问题的细节。
  • @juanpa.arrivillaga 我知道接受的答案不正确。那里的讨论仍然涵盖了很多内容,足以在这里解决这个问题。
  • @zvone 但是你不能在items 上调用next(),所以它的行为肯定不像迭代器?关于重复,我之前读过那个答案,但觉得它可能不够简单让我理解:P 现在回想起来,结合这里的答案,我确实明白了,所以很高兴接受重复如果那是正在进行的共识? (stackoverflow 的新手)
  • @E.Hazledine - 是的,但我猜 OP 想知道它的行为是像 python 2 中的 items 还是像 iteritems,在这种情况下,所有答案都是正确会导致错误的结论。因此我的简化评论

标签: python python-3.x dictionary iterator iterable


【解决方案1】:

不,不是。它是dict中项目的可迭代视图:

>>> next({}.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict_items' object is not an iterator
>>>

__iter__ 方法返回一个专门的迭代器实例:

>>> iter({}.items())
<dict_itemiterator object at 0x10478c1d8>
>>>

【讨论】:

    【解决方案2】:

    dict.items返回一个dict view,根据docs

    In [5]: d = {1: 2}
    
    In [6]: next(d.items())
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-6-945b6258a834> in <module>()
    ----> 1 next(d.items())
    
    TypeError: 'dict_items' object is not an iterator
    
    In [7]: next(iter(d.items()))
    Out[7]: (1, 2)
    

    回答您的问题,dict.items 不是迭代器。它是一个可迭代对象,支持len__contains__,并反映了对原始字典所做的更改:

    In [14]: d = {1: 2, 3: 4}
    
    In [15]: it = iter(d.items())
    
    In [16]: next(it)
    Out[16]: (1, 2)
    
    In [17]: d[3] = 5
    
    In [18]: next(it)
    Out[18]: (3, 5)
    

    【讨论】:

      【解决方案3】:

      你可以直接测试这个:

      from collections import Iterator, Iterable
      
      a = {}
      print(isinstance(a, Iterator))  # -> False
      print(isinstance(a, Iterable))  # -> True
      print(isinstance(a.items(), Iterator))  # -> False
      print(isinstance(a.items(), Iterable))  # -> True
      

      【讨论】:

        【解决方案4】:

        自己检查一下:

        d = {'a': 1, 'b': 2}
        
        it = d.items()
        print(next(it))
        

        这导致TypeError: 'dict_items' object is not an iterator

        另一方面,您始终可以将d.items() 迭代为:

        d = {'a': 1, 'b': 2}
        
        for k, v in d.items():
            print(k, v)
        

        或者:

        d = {'a': 1, 'b': 2}
        
        it = iter(d.items())
        print(next(it))  # ('a', 1)
        print(next(it))  # ('b', 2)
        

        【讨论】:

          猜你喜欢
          • 2018-02-04
          • 2018-02-16
          • 2012-12-13
          • 2020-01-21
          • 2018-07-14
          • 2019-11-21
          • 2012-08-20
          • 2023-03-25
          • 2011-03-17
          相关资源
          最近更新 更多