XIVN1987
V2EX  ›  Python

Python 3.15 将引入一个很方便的语法: Unpacking in Comprehensions

By XIVN1987 at 9 天前 · 2005 次点击

将二维数组 lists = [[1, 2], [3, 4], [5]] 展开成一维数组 [1, 2, 3, 4, 5]

之前写法:[x for L in lists for x in L]

Python 3.15 新语法:[*L for L in lists]

这个新语法真是简洁又直观,,这么符合直觉的语法怎么之前没想到添加??

13 条回复    2026-03-10 20:40:36 +08:00
JeffGe
   1
JeffGe  
   9 天前
确实很符合直觉,我没去查资料之前还以为这语法早就可以用了。
glacer
   2
glacer  
   9 天前
同,我自己想也是想到这样做。
yuruizhe
   3
yuruizhe  
   9 天前
我都是
from functools import reduce
from operator import add
reduce(add, [[1, 2], [3, 4], [5]])
绝不手写逻辑,100%掉包
HotieCutie
   4
HotieCutie  
   9 天前
js 直接 flat()
june4
   5
june4  
   9 天前   ❤️ 1
这点功能搞个新语法?不能 [x for L in lists.flat()] 吗
fisherman0459
   6
fisherman0459  
   9 天前
list(itertools.chain.from_iterable(lists))
Ketteiron
   7
Ketteiron  
   9 天前
@june4 #5 行不通,js 的 flat 只会对真正的数组进行操作,会使用类似 Array.isArray() 的判断,但 py 会产生歧义
在 py 里,字符串是无限递归的可迭代对象,如果要保持旧有设计就无法拍平,因此只能在一些工具函数里进行操作,硬编码一些判断
而 *L for L in lists 并非是用来解决二维数组拍平的,它解决的是无法在推导式中解包的设计缺陷。
szyp
   8
szyp  
   9 天前
之前还直接这么试过,报错,直觉上就应该这么实现
XIVN1987
   9
XIVN1987  
OP
   9 天前
@june4 python 中 *list 解包这个语法存在很久了,,现在只是又扩展了它的应用范围

比如下面这两个解包用法在之前的 python 版本中就有了,,所以才说这个新添加的用法符合直觉,,因为它和之前的解包语法完全一致:

In [10]: l1 = [1, 2, 3]

In [11]: l2 = [4, 5]

In [12]: [*l1, *l2]
Out[12]: [1, 2, 3, 4, 5]

In [13]: def test(a, b): print(a, b)

In [14]: test(*l2)
4 5
julyclyde
   10
julyclyde  
   8 天前
昨天看了那个 indently.io 的介绍视频,讲到一半说现在 alpha 版本还没支持
这人也太急了,都还没能实际演示的东西就开始做教学

另外,谁知道 indently.io 这人是哪儿的口音啊?发音总是带个 k 尾音
nonduality
   11
nonduality  
   8 天前
```python
sum(lists, [])
```
luckyc
   12
luckyc  
   6 天前
想要 js 的解构:

```javascript
const data = {"a":1,"b":2}
const {a, b} = data
console.log(a, b) // 1,2

```
iorilu
   13
iorilu  
   2 天前
可以, 不过我现在一般都用 3.12 版, 太新了很多库都不能用
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
© 2026 V2EX · 32ms · 3.9.8.5