python - 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
解决方案
这是有效iter
的,因为 应用于迭代器,返回相同的迭代器:
iterator.__iter__()
返回迭代器对象本身。这是允许容器和迭代器与 for 和 in 语句一起使用的必要条件。此方法对应于 Python/C API 中 Python 对象的类型结构的 tp_iter 槽。
在表达式列表中使用对象已经导致创建迭代器。假设已正确实现可迭代/迭代器协议,因此func(*iter(foo))
具有与 相同的效果。func(*foo)
推荐阅读
- java - java 8替代嵌套for循环
- reactjs - Formik Yup `.test()` 自定义验证无法正常工作
- mysql - sql如何调用内部联接以获取带有列表的名称
- angular - 关于 angular 自定义控件多文本输入问题
- html - 当我将它们设置为跨度 2 时,为什么我的网格行跨度为 1 行,而不是?
- ssl - 具有密码保护的 SSL 证书的 haproxy 无法启动
- mysql - 将 AWS Glue 连接到本地 MySQL 时出现问题,是 AWS VPC 吗?
- sql - SQL 排序和分组
- git - 如何让 IntelliJ IDEA 尊重 pre-commit-msg 钩子
- json - 在mongodb中导入集合.json