如果 range() 是 Python 3.3 中的生成器,为什么我不能在范围上调用 next()? [英] If range() is a generator in Python 3.3, why can I not call next() on a range?

查看:26
本文介绍了如果 range() 是 Python 3.3 中的生成器,为什么我不能在范围上调用 next()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我已经成为网络上错误信息的受害者,但我认为更有可能只是我误解了一些东西.根据我目前学到的知识,range() 是一个生成器,生成器可以用作迭代器.但是,这段代码:

myrange = range(10)打印(下一个(我的范围))

给我这个错误:

TypeError: 'range' 对象不是迭代器

我在这里错过了什么?我期望这会打印 0,并前进到 myrange 中的下一个值.我是 Python 新手,所以请接受我对这个相当基本的问题的歉意,但我在其他任何地方都找不到好的解释.

解决方案

range 是一类不可变的可迭代对象.它们的迭代行为可以与 lists 进行比较:您不能直接对它们调用 next;你必须使用 iter 来获得一个迭代器.

所以不,range 不是生成器.

您可能会想,为什么他们不直接将其设置为可迭代的"?好吧,ranges 有一些有用的属性,而这些属性是不可能的:

  • 它们是不可变的,因此可以用作字典键.
  • 它们具有 startstopstep 属性(从 Python 3.3 开始)、countindex 方法,它们支持 inlen__getitem__ 操作.
  • 您可以多次迭代相同的范围.
<小时><预><代码>>>>我的范围 = 范围(1, 21, 2)>>>myrange.start1>>>myrange.step2>>>myrange.index(17)8>>>myrange.index(18)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中值错误:18 不在范围内>>>it = iter(myrange)>>>它<range_iterator 对象在 0x7f504a9be960>>>>下一个(它)1>>>下一个(它)3>>>下一个(它)5

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 lists: 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, ranges 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 and step attributes (since Python 3.3), count and index methods and they support in, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆