Python中的迭代器(iter())函数。 [英] Iterator (iter()) function in Python.
本文介绍了Python中的迭代器(iter())函数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于字典,我可以使用 iter()
来迭代字典的键。
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
当我有如下的迭代器时,
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
为什么我不能这样使用
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()
的方式之一。
I guess this can be one of the ways of how iter()
is used.
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
推荐答案
所有这些工作都很好,除了错字 - 你可能意味着:
All of these work fine, except for a typo--you probably mean:
x = Counter(3,8)
for i in x:
print i
而不是
x = Counter(3,8)
for i in x:
print x
这篇关于Python中的迭代器(iter())函数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文