Python 中的迭代器 (iter()) 函数。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3938927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:25:39  来源:igfitidea点击:

Iterator (iter()) function in Python.

pythoniterator

提问by prosseek

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

对于字典,我可以iter()用于迭代字典的键。

y = {"x":10, "y":20}
for val in iter(y):
    print val

When I have the iterator as follows,

当我有如下迭代器时,

class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def next(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

Why can't I use it this way

为什么我不能这样使用

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

nor

也不

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

but this way?

但是这样?

for c in Counter(3, 8):
    print c

What's the usage of iter()function?

iter()函数的用途是什么?

ADDED

添加

I guess this can be one of the ways of how iter()is used.

我想这可能是如何iter()使用的方式之一。

class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def next(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

class Hello:
    def __iter__(self):
        return Counter(10,20)

x = iter(Hello())
for i in x:
    print i

采纳答案by Glenn Maynard

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

回答by Winston Ewert

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

我认为你的实际问题是print x当你想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.

iter()用于获取给定对象的迭代器。如果您有一个__iter__方法来定义 iter 将实际执行的操作。在您的情况下,您只能在计数器上迭代一次。如果您定义__iter__返回一个新对象,它将使它可以根据需要进行多次迭代。在您的情况下, Counter 已经是一个迭代器,这就是为什么返回自身是有意义的。