回答

收藏

如何从列表列表中制作平面列表

技术问答 技术问答 314 人阅读 | 0 人回复 | 2023-09-11

是否有从 Python 在列表列表中制作简单列表的快捷方式?, }0 B& b1 s: A' l
我可以for循环,但是有没有一些很酷的单线?) L' G, D1 t/ E8 {% A  r
我试过functools.reduce():
/ e) |4 G3 g6 R+ X+ j" `- h. W8 Q
    from functools import reducel = [1,2,3],[4,5,6],[7],[8,9]reduce(lambda x,y: x.extend(y),l)
    + Q4 ?" |% d9 I; j% `' U
但我收到了这个错误:
; ?% R. i( Q& Z6 n# ^
    Traceback (most recent call last):  File "",line 1,in   File "",line 1,in AttributeError: 'NoneType' object has no attribute 'extend'( p4 b8 I, s4 _& B
               * n+ I  |0 R) g; x
    解决方案:                                                                % i3 a: H! l7 R2 g
                                                                给出列表列表t,
( B7 y; T0 P6 |% `5 @! d
    flat_list = [item for sublist in t for item in sublist]
    ( f; Z* L) y9 C7 V2 Y* B
意思是:
3 ?9 {( z. e$ F, S% o# N
    flat_list = []for sublist in t:    for item in sublist:        flat_list.append(item)) @9 a* S! X7 v7 c6 r) s" r1 L
比到目前为止发布的快捷方式更快。(t列表要展平。
, E% e" J, k4 w以下是对应函数:
: ~$ G- }! {3 U2 {) h7 R4 i
    def flatten(t):    return [item for sublist in t for item in sublist]
    ! o2 y5 |2 c* d
你可以用作证据timeit标准库中的模块:* x. m- Y3 Z2 e$ O- f1 B- c
    $ python -mtimeit -s't=[1,2,3],[4,5,6],[7],[8,9]*99' '[item for sublist in t for item in sublist]'10000 loops,best of 3: 143 usec per loop$ python -mtimeit -s't=[1,2,3],[4,5,6],[7],[8,9]*99' 'sum(t,[])'1000 loops,best of 3: 969 usec per loop$ python -mtimeit -s't=[1,2,3],[4,5,6],[7],[8,9]*99' 'reduce(lambda x,y: x y,t)'1000 loops,best of 3: 1.1 msec per loop
    5 M3 F" O6 T3 @! K' O
说明:基于 (包括 )in 隐含使用sum)快捷的方法是,O(T**2)当有 T 个子列表-随着中间结果列表越来越长,每一步都会分配一个新的中间结果列表对象,所有项目都必须复制以前的中间结果(以及一些最终添加的新结果)。因此,假设每个子列表都有 k项目:前 k 项目来回复制 T-1 次,后 k 个项目 T-2 次,以此类推;从 1 到  T 排除的 x,总副本为 x 总和的 k 倍,即k * (T**2)/2。
$ `& c: i1 b$ D6 b& n列表推导式只生成一个列表,复制每个项目(从原住所到结果列表)一次。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则