2012-08-30 46 views
6

我想了解內置sum()功能,但是,在start參數已經蒸發腦海裏的工作:蟒蛇和功能 - `start`參數說明需要

  1. a=[[1, 20], [2, 3]] 
    b=[[[[[[1], 2], 3], 4], 5], 6] 
    >>> sum(b,a) 
    Traceback (most recent call last): 
        File "<stdin>", line 1, in <module> 
    TypeError: can only concatenate list (not "int") to list 
    >>> sum(a,b) 
    [[[[[[1], 2], 3], 4], 5], 6, 1, 20, 2, 3] 
    
  2. >>> a=[1,2] 
    >>> b=[3,4] 
    >>> sum(a,b) 
    Traceback (most recent call last): 
        File "<stdin>", line 1, in <module> 
    TypeError: can only concatenate list (not "int") to list 
    >>> sum(b,a) 
    Traceback (most recent call last): 
        File "<stdin>", line 1, in <module> 
    TypeError: can only concatenate list (not "int") to list 
    

我只是傻眼了這一點,不知道發生了什麼事。以下是python文檔必須說的:http://docs.python.org/library/functions.html#sum。這並沒有給出「如果開始不是字符串而不是整數?」的解釋。

+0

我只對累積和使用'start'參數,所以type只是'int'。我不認爲它是針對這種病理性病例的。:) – halex

+0

正如文檔中所指出的那樣:將'sum'限制爲數字:-),您將會減少頭痛。如果您必須連接嵌套列表,請做一些顯式構造 - 無論如何,您將擁有更多可維護的代碼。 – jsbueno

回答

14

總和就這樣的事情

def sum(values, start = 0): 
    total = start 
    for value in values: 
     total = total + value 
    return total 

sum([1,2],[3,4])展開類似[3,4] + 1 + 2,你可以看到嘗試添加數字和名單一起。

爲了使用sum生成列表,值應該是列表的列表,而start可以只是一個列表。您會在失敗的示例中看到該列表至少包含一些整數,而不是所有列表。

,你可能會認爲使用金額以列表的常見的情況是,以列表的列表轉換成一個列表

sum([[1,2],[3,4]], []) == [1,2,3,4] 

不過說真的,你不應該這樣做,因爲這將是緩慢的。

+0

更像'total = total + value'這就是爲什麼sum對於列表 –

+0

@gnibbler來說具有二次性能,這是真的。我沒有想過這個。 –

4
a=[[1, 20], [2, 3]] 
b=[[[[[[1], 2], 3], 4], 5], 6] 
sum(b, a) 

此錯誤與啓動參數無關。列表中有兩個項目b。其中之一是[[[[[1], 2], 3], 4], 5],另一個是6,並且列表和int不能被添加在一起。

sum(a, b) 

這增加:

[[[[[[1], 2], 3], 4], 5], 6] + [1, 20] + [2, 3] 

工作正常(因爲你剛剛加入名單列表)。

a=[1,2] 
b=[3,4] 
sum(a,b) 

這是試圖添加[3,4] + 1 + 2,這再次是不可能的。同樣,sum(b,a)正在添加[1, 2] + 3 + 4

如果開始不是字符串而不是整數?

sum無法對字符串進行求和。請參閱:

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

其中一個是已經有跡象,但在其他的答案沒有明確規定的事情之一是,start值定義爲type的返回值和物品被總結。因爲缺省值是start=0(當然,0是一個整數),所以iterable中的所有項必須是整數(或者使用與整數一起使用的__add__方法的類型)。其他的例子所提到的串聯列表:

sum([[1,2],[3,4]], []) == [1,2,3,4]

timedate.timedelta對象:

sum([timedelta(1), timedelta(2)], timedelta()) == timedelta(3))。

請注意,這兩個示例均將可迭代類型的空對象作爲開始參數傳遞,以避免出現TypeError: unsupported operand type(s) for +: 'int' and 'list'錯誤。