首页 > 解决方案 > Python unpack iterator

问题描述

I know *operator in Python is used to unpack iterable, such as unpack a list.

However, in practice, we also use * operator to unpack iterator, but I haven't found a document explaining it.

See example:

>>> a = [1,2,3]
>>> print(a)
[1, 2, 3]

unpack iterable

>>> print(*a)
1,2,3

unpack iterator

>>> it = iter(a)
>>> print(*it)
1,2,3

标签: pythoniterator

解决方案


这是有效iter的,因为 应用于迭代器,返回相同的迭代器:

iterator.__iter__()
返回迭代器对象本身。这是允许容器和迭代器与 for 和 in 语句一起使用的必要条件。此方法对应于 Python/C API 中 Python 对象的类型结构的 tp_iter 槽。

在表达式列表中使用对象已经导致创建迭代器。假设已正确实现可迭代/迭代器协议,因此func(*iter(foo))具有与 相同的效果。func(*foo)


推荐阅读