将数字列表加起来比使用for循环更快的方法?

not*_*atr 10 python algorithm for-loop

有没有办法比使用for循环更快地总结一个数字列表,可能在Python库中?或者只是多线程/矢量处理才能有效地完成?

编辑:只是为了澄清,它可以是任何数字的列表,未分类,只是来自用户的输入.

Chr*_*tow 32

您可以使用sum()来求和数组的值.

a = [1,9,12]
print sum(a)
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 5

另一种用循环时间总结列表的方法:

    s = reduce(lambda x, y: x + y, l)
Run Code Online (Sandbox Code Playgroud)

  • 您应该使用operator.add而不是lambda.使用lambda对前100000个数字求和为34ms,而使用operator.add仅为19ms.(总和比两者都好15ms). (9认同)