迭代器vs可迭代? [英] Iterator vs Iterable?

查看:89
本文介绍了迭代器vs可迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(对于python 3)

在python文档中,您可以看到 list()函数需要迭代.

In the python docs, you can see that the list() function takes an iterable.

在python文档中,您还可以看到 c1>函数需要一个迭代器.

In the python docs, you can also see that the next() funciton takes an iterator.

所以我在IDLE中做到了:

So I did this in IDLE:

>>> var = map(lambda x: x+5, [1,2,3])
>>> var
>>> next(v)
>>> list(v)

哪个给出输出:

<map object at 0x000000000375F978>
6
[7,8]

坦率地说,这不是我所期望的.映射对象是迭代器还是可迭代的?有什么区别吗?显然list()next()函数都可以在地图对象上使用,无论它是什么.

Frankly, this isn't what I expected. Is a map object an iterator or an iterable? Is there even a difference? Clearly both the list() and next() functions work on the map object, whatever it is.

为什么它们都起作用?

推荐答案

迭代器是可迭代的,但不一定是迭代器.

An iterator is an iterable, but an iterable is not necessarily an iterator.

可迭代对象是定义了__iter__方法的任何内容-例如列表和元组以及迭代器.

An iterable is anything that has an __iter__ method defined - e.g. lists and tuples, as well as iterators.

迭代器是迭代器的子集,其值不能一次访问,因为它们不会一次存储在内存中.这些可以使用mapfilteriter之类的函数以及使用yield的函数生成.

Iterators are a subset of iterables whose values cannot all be accessed at the same time, as they are not all stored in memory at once. These can be generated using functions like map, filter and iter, as well as functions using yield.

在您的示例中,map返回一个迭代器,它也是一个可迭代的,这就是两个函数都可使用它的原因.但是,如果我们以一个列表为例:

In your example, map returns an iterator, which is also an iterable, which is why both functions work with it. However, if we take a list for instance:

>>> lst = [1, 2, 3]
>>> list(lst)
[1, 2, 3]
>>> next(lst)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    next(lst)
TypeError: 'list' object is not an iterator

我们可以看到next抱怨,因为该列表是可迭代的,而不是 iterator .

we can see that next complains, because the list, an iterable, is not an iterator.

这篇关于迭代器vs可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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