python - 为什么 *x, 在 python 3 中解压映射对象?

标签 python python-3.x iterable-unpacking

在 Python 3 中,以下返回一个 map 对象:

map(lambda x: x**2, range(10))

如果我们想把这个对象变成一个列表,我们可以使用 list(mapobject) 将它转换为一个列表。但是,我通过代码打高尔夫球发现

*x, = mapobject

使 x 成为一个列表。为什么在 Python 3 中允许这样做?

最佳答案

这是一个扩展的可迭代拆包示例,由 PEP 3132 引入 Python 3 :

This PEP proposes a change to iterable unpacking syntax, allowing to specify a "catch-all" name which will be assigned a list of all items not assigned to a "regular" name.

An example says more than a thousand words:

>>> a, *b, c = range(5)
>>> a
0
>>> c
4
>>> b
[1, 2, 3]

像往常一样,在 Python 中,单例元组使用尾随逗号表示,因此扩展等效于此:

>>> x, = [1]
>>> x
1

……这是:

>>> *x, = range(3)
>>> x
[0, 1, 2]

关于python - 为什么 *x, 在 python 3 中解压映射对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48292653/

相关文章:

python-3.x - Gridsearchcv 与贝叶斯优化

python - 扩展解包不会在列表中创建单独的项目

python 将列表的元素分配到sql查询的一部分

Python 在变量后同时插入回车符和换行符,而不仅仅是换行符

python 样式指南 pep 8。多行多列字典

Python 名称未定义但计算结果为真。如何?

python - Django REST Framework 多对多创建和更新

python-3.x - 是否有服务器 Python 3 websocket 模块?

python - Next() 跳过列表中的实际项和下一项,而它应该只跳过实际项

python - 如果我开始返回更多数据,则返回不会破坏客户端代码的不可打包值的可迭代对象