嘗試編寫一個函數,該函數獲取每個列表的總和並將單個值返回到新的單個列表中。 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函數在這裏是不允許的,因爲它是嵌套循環的練習。
感謝。
在第一個'for'循環中設置'total = 0'。還要確保你發佈了正確的縮進代碼。 – Julien