在 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/