2016-08-09 46 views
4

嘗試編寫一個函數,該函數獲取每個列表的總和並將單個值返回到新的單個列表中。 E.g不使用SUM函數的嵌套列表之和(練習)

[[2, 7, 6], [9, 5, 1], [4, 3, 8]] 

成爲

[15, 15, 15] 

我到目前爲止有:

def row_sums(square): 
    total_list = [] 
    total = 0 
    for i in square: 
     for j in i: 
      total += j 
     total_list.append(total) 
    return total_list  

但這只是積累每個列表到對方造成:

[15, 30, 45] 

我不知道如何保持每個列表的總和在這裏分開。 SUM函數在這裏是不允許的,因爲它是嵌套循環的練習。

感謝。

+2

在第一個'for'循環中設置'total = 0'。還要確保你發佈了正確的縮進代碼。 – Julien

回答

3

您需要重置您的total計數器,然後再開始每個計數器。 另外,你不需要在外面聲明它,因爲你只會在裏面使用它。

def row_sums(square): 
    total_list = [] 
    for i in square: 
     total = 0 
     for j in i: 
      total += j 
     total_list.append(total) 
    return total_list 
+0

爲什麼倒票? – levi

3

錯誤是你沒有在每次循環後重新初始化變量total。取而代之的是,第一for循環初始化sum = 0裏面,他就像這樣:

def row_sums(square): 
    total_list = [] 
    for i in square: 
     total = 0 
     for j in i: 
      total += j 
     total_list.append(total) 
    return total_list 
+0

有道理。至少這是非常簡單的事情。謝謝一堆。 –

+0

@RobertHemingway你非常歡迎。如果你喜歡我的回答,請注意。 –

+0

爲什麼我低調? –

1

您需要零時,您總爲每個列表。

def row_sums(square): 
    total_list = [] 
    total = 0 
    for i in square: 
     for j in i: 
      total += j 
     total_list.append(total) 
     total = 0 
    return total_list 
2

只是爲了好玩:

>>> list = [[2, 7, 6], [9, 5, 1], [4, 3, 8]] 
>>> import functools 
>>> [functools.reduce(lambda x, y: x + y, sublist, 0) for sublist in list] 
[15, 15, 15] 

餘did't使用sum :)

你可以閱讀更多關於functools.reducehere

編輯:Sevanteri在評論中指出,你也可以使用[functools.reduce(int.__add__, sublist, 0) for sublist in list] (如果你真的想駕駛你的老師瘋了!)

+2

因爲已經有一個整數的二進制和函數,所以你可以用int替換這個lambda函數。__add__'。 :) – Sevanteri

+0

@ Sevanteri哈哈哈我喜歡這個主意! –

+1

使用'int .__ add__'看起來有點難看,我寧願使用'operator.add' :) – Copperfield

0

是不同的,扁平化的列表,並使用一臺發電機(假設子表是相同的長度):

def _notsum2(lists): 
    per_yield = len(lists) 
    total = 0 
    for ind, next in enumerate(val for sublist in lists for val in sublist): 
     if ind % per_yield == 0 and ind: 
      yield total 
      total = 0 
     total += next 
    yield total 


if __name__ == '__main__': 
    li = [[2, 7, 6], [9, 5, 1], [4, 3, 8]] 
    print [g for g in _notsum2(li)] 
-1

你也可以做到這一點使用map和列表理解爲:

l=[[2, 7, 6], [9, 5, 1], [4, 3, 8]] 
a,b,c=[x for x in l] 
map(lambda x,y,z:x+y+z, a,b,c) 
-2

[sum(i) for i in zip(*[[2, 7, 6], [9, 5, 1], [4, 3, 8]])]

bultin zip func正是你需要的東西

+1

OP希望不用'sum'來完成它,也希望每個子列表中元素的總和不是與所有子列表的組合 – Copperfield