Python 的 sum() 会将字符串列表加在一起。有什么用?

标签 python sum

我遇到了一个奇怪的 Python 习语(无论如何在我看来),并确定这是一个错误。但随后它运行了。

>>> sum([['a'], ['b']], [])
['a', 'b']

本质上是一样的

>>> [] + ['a'] + ['b']
['a', 'b']

sum() 的默认值为 0,但它允许您指定不同的默认值,在这种情况下它必须是另一个列表(空或其他)。

这真的只是一种令人费解的说法

>>> ['a'] + ['b']
['a', 'b']

更简单易读。

那么有性能差异吗?

>>> import timeit
>>> from string import ascii_lowercase, ascii_uppercase

>>> lower = list(ascii_lowercase)
>>> upper = list(ascii_uppercase)

>>> timeit.timeit('lower + upper', globals=globals())
0.3070615209871903

>>> timeit.timeit('sum([lower, upper], [])', globals=globals())
0.7599097189959139

是的,但不是很好,所以没有什么可推荐的。

sum() 添加对象的能力还有其他用途吗?

最佳答案

sum([['a'], ['b']], [])

此处 sum 只是按照设计的目的进行操作。只需在其输入上使用加法运算符。在这种情况下,输入是两个列表,列表中恰好定义了 __add__ 方法。

>>> [].__add__
<method-wrapper '__add__' of list object at 0x108f5c948>

您看到的性能影响是因为创建了中间列表。当您执行 [] + ['a'] 时,会创建一个新列表,其中只有 'a'。当您向其中添加 'b' 时,将创建另一个列表。


除此之外,文档还推荐了 sum 的替代方案,

For some use cases, there are good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling ''.join(sequence). To add floating point values with extended precision, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().

在您的情况下,您正在尝试连接一系列可迭代对象,首选方法是使用 itertools.chain()

关于Python 的 sum() 会将字符串列表加在一起。有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40670670/

相关文章:

c++ - OpenCL数据并行求和成一个变量

sql - 获取数量的平均值

mysql - 如何根据另一列的值之和选择一行?

prolog - 在 Prolog 中计算总和

python - slqlalchemy UniqueConstraint VS 索引(唯一=真)

javascript - 添加多个输入实时 javascript

python - [:, :,::-1] 在python中是什么意思?

python - 为什么我的 Django 表单没有设置初始值?

python - 如何使用norm.ppf()?

python - 从循环中创建值列表