Iterator (iter()) function in Python.

前端 未结 2 1200
独厮守ぢ
独厮守ぢ 2021-02-05 10:31

For dictionary, I can use iter() for iterating over keys of the dictionary.

y = {\"x\":10, \"y\":20}
for val in iter(y):
    print val
相关标签:
2条回答
  • 2021-02-05 11:11

    I think your actual problem is that you print x when you mean to print i

    iter() is used to obtain an iterator over a given object. If you have an __iter__ method that defines what iter will actually do. In your case you can only iterate over the counter once. If you defined __iter__ to return a new object it would make it so that you could iterate as many times as you wanted. In your case, Counter is already an iterator which is why it makes sense to return itself.

    0 讨论(0)
  • 2021-02-05 11:14

    All of these work fine, except for a typo--you probably mean:

    x = Counter(3,8)
    for i in x:
        print i
    

    rather than

    x = Counter(3,8)
    for i in x:
        print x
    
    0 讨论(0)
提交回复
热议问题