2013-09-30 47 views
-6

如何創建一個函數來添加給定列表中的所有數字?在Python中。 事情是這樣的:在列表中添加數字。 Python

list = [8, 5, 6, 7, 5, 7] 

def sum(list): 
    ??? 
+0

你可以使用'sum(list)'。順便說一句,不要調用你的變量'list' - 你會覆蓋標準的數據結構 –

+5

對不起,但我downvoted,因爲你甚至沒有嘗試過你的代碼行...... – tamasgal

+0

lol @septi他確實發佈了一個代碼沒有嘗試! –

回答

0

它已經存在,沒有必要把它定義:

sum([8,5,6,7,5,7]) 
3

要回答你問嚴格什麼:

# notice how I've named it 'lst' not 'list'—'list' is the built in; don't override that 
def sum(lst): 
    ret = 0 
    for item in lst; 
     ret += item 
    return ret 

或者,如果你喜歡函數式編程:

def sum(lst): 
    return reduce(lambda acc, i: acc + i, lst, 0) 

甚至:

import operator 

def sum(lst): 
    return reduce(operator.add, lst, 0) 

你甚至可以使其在非數字輸入,工作當中內置sum()不能做(因爲它是作爲高效率的C代碼實現),但是這確實進入過範疇 - 工程:

def sum(lst, initial=None): 
    if initial is None: 
     initial = type(lst[0])() if lst else None 
    return reduce(lambda acc, i: acc + i, lst, initial) 

>>> sum([1, 2, 3]) 
6 
>>> sum(['hello', 'world']) 
'hello world' 
>>> sum([[1, 2, 3], [4, 5, 6]]) 
[1, 2, 3, 4, 5, 6] 

但由於Python的名單是無類型的,在空單的情況下,該函數將返回None

注意:但是,正如其他人指出的,這隻對學習目的有用;在現實生活中,您使用內置的sum()功能。