为什么范围对象“不是迭代器"? [英] Why is the range object "not an iterator"?

查看:75
本文介绍了为什么范围对象“不是迭代器"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个,并期望0:

>>> x = range(20)
>>> next(x)

相反,我得到了:

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

TypeError: 'range' object is not an iterator

但是我以为是发电机吗?

But I thought it was a generator?

最初的回答产生了我最初对自己说的同样的话:这是一个可迭代的过程,而不是干预者.但是,如果这两个只是生成器,那么这并不能解释为什么它会起作用:

The initial answer yielded the same thing I initially said to myself: it's an iterable, not an interator. But then, that wouldn't explain why this works, if both are simply generators:

>>> x = (i for i in range(30))
>>> next(x)
0

推荐答案

range返回可迭代的,而不是迭代器.当需要迭代时,它可以使迭代器. 它不是生成器.

range returns an iterable, not an iterator. It can make iterators when iteration is necessary. It is not a generator.

生成器表达式的计算结果为迭代器(因此也是可迭代的).

A generator expression evaluates to an iterator (and hence an iterable as well).

这篇关于为什么范围对象“不是迭代器"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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