Iterator (iter()) function in Python.

前端 未结 2 1199
独厮守ぢ
独厮守ぢ 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.

提交回复
热议问题