V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
XIVN1987
V2EX  ›  Python

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

  •  
  •   XIVN1987 · 11 小时 40 分钟前 · 1117 次点击

    将二维数组 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]

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

    9 条回复    2026-03-03 13:46:10 +08:00
    JeffGe
        1
    JeffGe  
       11 小时 30 分钟前
    确实很符合直觉,我没去查资料之前还以为这语法早就可以用了。
    glacer
        2
    glacer  
       11 小时 29 分钟前
    同,我自己想也是想到这样做。
    yuruizhe
        3
    yuruizhe  
       11 小时 14 分钟前
    我都是
    from functools import reduce
    from operator import add
    reduce(add, [[1, 2], [3, 4], [5]])
    绝不手写逻辑,100%掉包
    HotieCutie
        4
    HotieCutie  
       11 小时 12 分钟前
    js 直接 flat()
    june4
        5
    june4  
       10 小时 6 分钟前   ❤️ 1
    这点功能搞个新语法?不能 [x for L in lists.flat()] 吗
    fisherman0459
        6
    fisherman0459  
       9 小时 58 分钟前
    list(itertools.chain.from_iterable(lists))
    Ketteiron
        7
    Ketteiron  
       9 小时 42 分钟前
    @june4 #5 行不通,js 的 flat 只会对真正的数组进行操作,会使用类似 Array.isArray() 的判断,但 py 会产生歧义
    在 py 里,字符串是无限递归的可迭代对象,如果要保持旧有设计就无法拍平,因此只能在一些工具函数里进行操作,硬编码一些判断
    而 *L for L in lists 并非是用来解决二维数组拍平的,它解决的是无法在推导式中解包的设计缺陷。
    szyp
        8
    szyp  
       9 小时 36 分钟前
    之前还直接这么试过,报错,直觉上就应该这么实现
    XIVN1987
        9
    XIVN1987  
    OP
       9 小时 20 分钟前
    @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
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   2826 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 15:06 · PVG 23:06 · LAX 07:06 · JFK 10:06
    ♥ Do have faith in what you're doing.