Python总结,为什么不是字符串? [英] Python sum, why not strings?

查看:214
本文介绍了Python总结,为什么不是字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python具有内置函数 sum ,这实际上相当于:

Python has a built in function sum, which is effectively equivalent to:

def sum2(iterable, start=0):
    return start + reduce(operator.add, iterable)

除了字符串以外的所有类型的参数。它适用于数字和列表,例如:

for all types of parameters except strings. It works for numbers and lists, for example:

 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

为什么字符串被特别遗漏?

Why were strings specially left out?

 sum( ['foo','bar'], '') # TypeError: sum() can't sum strings [use ''.join(seq) instead]
 sum2(['foo','bar'], '') = 'foobar'

我似乎记得在Python列表中讨论的原因,所以解释或一个线程的链接解释它将是正常的。

I seem to remember discussions in the Python list for the reason, so an explanation or a link to a thread explaining it would be fine.

编辑:我知道标准的方法是做加入。我的问题是为什么禁止使用字符串金额的选项,而不会禁止列举。

Edit: I am aware that the standard way is to do "".join. My question is why the option of using sum for strings was banned, and no banning was there for, say, lists.

编辑2 :虽然我认为这是不需要的,因为我得到的所有好的答案,问题是:为什么总和工作在一个可迭代的包含数字或一个可迭代的包含列表,但不是一个可迭代的包含字符串?

Edit 2: Although I believe this is not needed given all the good answers I got, the question is: Why does sum work on an iterable containing numbers or an iterable containing lists but not an iterable containing strings?

推荐答案

Python尝试阻止您从求和字符串。你应该加入他们:

Python tries to discourage you from "summing" strings. You're supposed to join them:

"".join(list_of_strings)

快一点,使用更少的内存。

It's a lot faster, and uses much less memory.

一个快速的基准: p>

A quick benchmark:

$ 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的编辑):至于为什么字符串显然被挑出,我相信这只是一个普通案例的优化问题,以及执行最佳实践:您可以使用。加入更快的字符串,因此明确禁止总和中的字符串将指向新手。

Edit (to answer OP's edit): As to why strings were apparently "singled out", I believe it's simply a matter of optimizing for a common case, as well as of enforcing best practice: you can join strings much faster with ''.join, so explicitly forbidding strings on sum will point this out to newbies.

BTW,这个限制已经到了永远,即由于 sum 被添加为内置函数( rev。32347

BTW, this restriction has been in place "forever", i.e., since the sum was added as a built-in function (rev. 32347)

这篇关于Python总结,为什么不是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆