Python具有内置函数sum
,实际上等效于:
def sum2(iterable, start=0):
return start + reduce(operator.add, iterable)
适用于所有类型的参数(字符串除外)。它适用于数字和列表,例如:
sum([1,2,3], 0) = sum2([1,2,3],0) = 6 #Note: 0 is the default value for start, but I include it for clarity
sum({888:1}, 0) = sum2({888:1},0) = 888
为什么特地省去了弦乐?
sum( ['foo','bar'], '') # TypeError: sum() can't sum strings [use ''.join(seq) instead]
sum2(['foo','bar'], '') = 'foobar'
我似乎还记得其中原因的Python列表中的讨论,因此可以使用一个解释或一个指向该解释的线程的链接。
编辑:我知道标准方法是这样做"".join
。我的问题是为什么禁止对字符串使用sum的选项,而列表却没有禁止的选项。
编辑2:尽管我认为鉴于我得到的所有好的答案都不需要这样做,但问题是:为什么sum在可迭代的包含数字或可迭代的包含列表而不在可迭代的包含字符串上起作用?
Python试图阻止您“添加”字符串。您应该加入他们的行列:
"".join(list_of_strings)
它快得多,并且使用的内存更少。
快速基准:
$ python -m timeit -s 'import operator; strings = ["a"]*10000' 'r = reduce(operator.add, strings)'
100 loops, best of 3: 8.46 msec per loop
$ python -m timeit -s 'import operator; strings = ["a"]*10000' 'r = "".join(strings)'
1000 loops, best of 3: 296 usec per loop
编辑(回答OP的编辑):关于为什么字符串显然是“单一”的,我相信这只是针对常见情况进行优化以及实施最佳实践的问题:您可以使用''更快地连接字符串。加入,因此明确禁止使用字符串sum
会向新手指出。
顺便说一句,此限制已“永远存在”,即,由于将限制sum
添加为内置函数(修订版32347)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句