如果 range() 是 Python 3.3 中的生成器,为什么我不能在范围上调用 next()? [英] If range() is a generator in Python 3.3, why can I not call next() on a range?
问题描述
也许我已经成为网络上错误信息的受害者,但我认为更有可能只是我误解了一些东西.根据我目前学到的知识,range() 是一个生成器,生成器可以用作迭代器.但是,这段代码:
myrange = range(10)打印(下一个(我的范围))
给我这个错误:
TypeError: 'range' 对象不是迭代器
我在这里错过了什么?我期望这会打印 0,并前进到 myrange
中的下一个值.我是 Python 新手,所以请接受我对这个相当基本的问题的歉意,但我在其他任何地方都找不到好的解释.
range
是一类不可变的可迭代对象.它们的迭代行为可以与 list
s 进行比较:您不能直接对它们调用 next
;你必须使用 iter
来获得一个迭代器.
所以不,range
不是生成器.
您可能会想,为什么他们不直接将其设置为可迭代的"?好吧,range
s 有一些有用的属性,而这些属性是不可能的:
- 它们是不可变的,因此可以用作字典键.
- 它们具有
start
、stop
和step
属性(从 Python 3.3 开始)、count
和index
方法,它们支持in
、len
和__getitem__
操作. - 您可以多次迭代相同的
范围
.
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))
gives me this error:
TypeError: 'range' object is not an iterator
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
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
.
So no, range
is not a generator.
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:
- 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屋!