对于字典,我可以iter()用来迭代字典的键.
y = {"x":10, "y":20}
for val in iter(y):
print val
Run Code Online (Sandbox Code Playgroud)
当我有迭代器如下,
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
Run Code Online (Sandbox Code Playgroud)
为什么我不能这样使用它
x = Counter(3,8)
for i in x:
print x
Run Code Online (Sandbox Code Playgroud)
也不
x = Counter(3,8)
for i in iter(x):
print x
Run Code Online (Sandbox Code Playgroud)
但这样呢?
for c in Counter(3, 8):
print c
Run Code Online (Sandbox Code Playgroud)
功能的用途是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
Run Code Online (Sandbox Code Playgroud)
Gle*_*ard 16
所有这些工作都很好,除了拼写错误 - 你可能意味着:
x = Counter(3,8)
for i in x:
print i
Run Code Online (Sandbox Code Playgroud)
而不是
x = Counter(3,8)
for i in x:
print x
Run Code Online (Sandbox Code Playgroud)
我认为你的实际问题是print x你的意思print i
iter()用于获取给定对象上的迭代器.如果你有一个__iter__方法来定义它实际上会做什么.在您的情况下,您只能在柜台上迭代一次.如果您定义__iter__为返回一个新对象,那么它将使您可以根据需要迭代多次.在你的情况下,Counter已经是一个迭代器,这就是为什么返回它自己是有意义的.
| 归档时间: |
|
| 查看次数: |
37181 次 |
| 最近记录: |