如果range()是Python 3.3中的生成器,为什么不能在范围上调用next()? [英] If range() is a generator in Python 3.3, why can I not call next() on a range?
问题描述
也许我已经成为网络错误信息的受害者,但我认为更可能是我误解了一些信息.根据我到目前为止所学的知识,range()是一个生成器,并且生成器可以用作迭代器.但是,此代码:
Perhaps I've fallen victim to misinformation on the web, but I think it's more likely just that I've misunderstood something. Based on what I've learned so far, range() is a generator, and generators can be used as iterators. However, this code:
myrange = range(10)
print(next(myrange))
给我这个错误:
TypeError: 'range' object is not an iterator
我在这里想念什么?我期望它打印0,并前进到myrange
中的下一个值.我是Python的新手,所以请接受我对这个基本问题的歉意,但在其他任何地方都找不到很好的解释.
What am I missing here? I was expecting this to print 0, and to advance to the next value in myrange
. I'm new to Python, so please accept my apologies for the rather basic question, but I couldn't find a good explanation anywhere else.
推荐答案
range
是一类不变的可迭代对象.可以将它们的迭代行为与list
进行比较:您不能直接对它们调用next
;您必须使用iter
获取一个迭代器.
range
is a class of immutable iterable objects. Their iteration behavior can be compared to list
s: you can't call next
directly on them; you have to get an iterator by using iter
.
所以不,range
不是生成器.
您可能会想,为什么他们没有使其直接可迭代"?好吧,range
具有一些有用的属性,而这种方式是不可能的:
You may be thinking, "why didn't they make it directly iterable"? Well, range
s have some useful properties that wouldn't be possible that way:
- 它们是不可变的,因此可以用作字典键.
- 它们具有
start
,stop
和step
属性(自Python 3.3起),count
和index
方法,并且它们支持in
,len
和__getitem__
操作. li>
- 您可以多次遍历同一个
range
.
- They are immutable, so they can be used as dictionary keys.
- They have the
start
,stop
andstep
attributes (since Python 3.3),count
andindex
methods and they supportin
,len
and__getitem__
operations. - You can iterate over the same
range
multiple times.
>>> myrange = range(1, 21, 2)
>>> myrange.start
1
>>> myrange.step
2
>>> myrange.index(17)
8
>>> myrange.index(18)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 18 is not in range
>>> it = iter(myrange)
>>> it
<range_iterator object at 0x7f504a9be960>
>>> next(it)
1
>>> next(it)
3
>>> next(it)
5
这篇关于如果range()是Python 3.3中的生成器,为什么不能在范围上调用next()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!