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

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

问题描述

也许我已经成为网络错误信息的受害者,但我认为更可能是我误解了一些信息.根据我到目前为止所学的知识,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 lists: 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, ranges have some useful properties that wouldn't be possible that way:

  • 它们是不可变的,因此可以用作字典键.
  • 它们具有startstopstep属性(自Python 3.3起),countindex方法,并且它们支持inlen__getitem__操作.
  • li>
  • 您可以多次遍历同一个range.
  • 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天全站免登陆