Python中的迭代器(iter())函数。
对于字典,我可以使用 iter()
来遍历字典的键。
y = {"x":10, "y":20}
for val in iter(y):
print val
当我有一个迭代器时,如下所示,
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
为什么我不能这样使用它呢?
x = Counter(3,8)
for i in x:
print x
也不能这样
x = Counter(3,8)
for i in iter(x):
print x
但是这样可以呢?
for c in Counter(3, 8):
print c
iter()
函数的用途是什么?
补充说明
我想这可能是 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
2 个回答
8
我觉得你真正的问题是,你在用 print x
打印的时候,其实应该用 print i
。
iter()
是用来获取一个对象的迭代器的。如果你有一个 __iter__
方法,它会定义迭代器的具体行为。在你的情况中,你只能对计数器进行一次迭代。如果你把 __iter__
定义成返回一个新的对象,那样你就可以进行多次迭代了。而在你的例子中,Counter 本身已经是一个迭代器,所以返回它自己是合理的。
17
这些都没问题,除了一个小错误——你可能是想说:
x = Counter(3,8)
for i in x:
print i
而不是
x = Counter(3,8)
for i in x:
print x