2015-04-02 72 views
-1

sum()函數只能使用數字,而不能使用字符串。爲什麼Python builin sum()函數不支持字符串?

int_lst = [1, 2] 
    sum(int_lst) 
=> 3 

    str_lst = ['a', 'b'] 
    sum(str_lst) 
Traceback (most recent call last): 
    File "python", line 1, in <module> 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

我發現這種行爲奇怪,因爲sum()功能僅僅是一個做多reduce(lambda i, sum:i+sum) Python的方式。並減少讓我來concincate字符串,並且sum()不。

From python documentation for sum()

可迭代的項目是正常的數字,並開始值不 允許爲一個字符串。

那麼爲什麼?

OOP教我們做多形性的東西,因爲它的靈活性。

+0

可能重複[Python總和,爲什麼不是字符串?](https://stackoverflow.com/questions/3525359/python-sum-why-not-strings) – 2017-11-15 17:14:42

回答

5

總結字符串是非常低效;在循環中求和字符串要求爲每個要串聯的兩個字符串創建一個新字符串,只有當下一個字符串與該結果連接時纔會再次銷燬。

例如,對於總結['foo', 'bar', 'baz', 'spam', 'ham', 'eggs']你創建'foobar',然後'foobarbaz',然後'foobarbazspam',然後'foobarbazspamham',最後'foobarbazspamhameggs',丟棄所有,但最後一個字符串對象。

你會使用str.join()方法來代替:

''.join(str_list) 

這會在組成字符串的內容一個新的字符串和副本。

注意sum()使用默認啓動的0價值,這就是爲什麼你會得到你的具體異常消息:

>>> 0 + '' 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

你可以給sum()不同的初始值作爲第二個參數;對於會給你一個更有意義的錯誤信息的字符串:

>>> sum(['foo', 'bar'], '') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: sum() can't sum strings [use ''.join(seq) instead] 

該函數不限於數字;您可以將其用於定義__add__操作的任何其他類型,但您必須指定合理的起始值。你可以「和」名單,例如:

>>> sum([['foo', 'bar'], ['ham', 'spam']], []) 
['foo', 'bar', 'ham', 'spam'] 

但要注意的第二個(start)參數的值[]!這與求和字符串一樣低效。有效的方法將使用list(itertools.chain.from_iterable(list_of_lists))

+0

'list(chain.from_iterable(l))'會更快更快 – 2015-04-02 16:35:58

+0

@PadraicCunningham:你有時間嗎?因爲無論哪種方式,列表將被迭代。 – 2015-04-02 16:36:55

+0

我一直髮現它速度更快。在'l = [['foo','bar'],['ham','spam']] * 100000'上,它是12ms對8.3ms。 – 2015-04-02 16:39:22

相關問題