gpt4 book ai didi

python - 我可以用 sum() 加入列表吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:04:11 25 4
gpt4 key购买 nike

使用 sum() 进行列表连接是 pythonic 吗?

>>> sum(([n]*n for n in range(1,5)),[])
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

最佳答案

不,不是,实际上是 shlemiel the painter algorithm .因为每次它想要连接一个新列表时,它都必须从头开始遍历整个列表。 (有关更多信息,请阅读 Joel 的这篇文章: http://www.joelonsoftware.com/articles/fog0000000319.html )

最 pythonic 的方法是使用列表理解:

In [28]: [t for n in range(1,5) for t in [n]*n ]
Out[28]: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

或者itertools.chain:

In [29]: from itertools import chain

In [32]: list(chain.from_iterable([n]*n for n in range(1,5)))
Out[32]: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

或者作为纯基于生成器的方法,您可以使用 repeat 而不是乘以列表:

In [33]: from itertools import chain, repeat

# In python2.X use xrange instead of range
In [35]: list(chain.from_iterable(repeat(n, n) for n in range(1,5)))
Out[35]: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

或者,如果您对 numpy 感兴趣,或者您想要一种超快速的方法,这里有一个:

In [46]: import numpy as np
In [46]: np.repeat(np.arange(1, 5), np.arange(1, 5))
Out[46]: array([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])

关于python - 我可以用 sum() 加入列表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39435401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com