2017-08-12 20 views
0

我需要将未知数量的列表中的每个索引一起添加到一个列表中。通过索引添加未知数量的列表

我的意思的例子:

list_a = [1,2,3,4,5] 
list_b = [2,4,6,8,10] 
list_c = [3,6,9,12,15] 

def sum_lists(): 
    temp_list = [] 

    for index in range(len(list_a)): 
     temp_list.append(list_a[index] + list_b[index] + list_c[index]) 

    return temp_list 

total = sum_lists() 

我的示例代码的预期结果将是:

total = [6,12,18,24,30] 

我将如何完成列表的未知量的总和,例如20个列表?我不需要在数以千计的列表中添加这些内容,但我不知道最初必须添加多少个列表。

任何帮助将不胜感激。所有的列表将具有相同的长度。

+0

如果你要得到一个列表的总和(如:'[1,2,3]→6') ,你会怎么做? – Ryan

+2

'邮编'的名单。在得到的元组列表中,对每个元组的元素进行求和。查看如何使用'zip'和'sum'方法。 – Prune

+1

'[zip(list_a,list_b,list_c)]中的els的总和(els)]。正如@Prune所说,它使用['sum'](https://docs.python.org/3/library/functions.html#sum)和['zip'](https://docs.python.org /3/library/functions.html#zip)内置方法。 –

回答

0

创建一个列表的列表:

In [124]: big_list = [list_a, list_b, list_c] 

现在,zip举起手来使用map适用sum每一个:

In [125]: list(map(sum, zip(*big_list))) 
Out[125]: [6, 12, 18, 24, 30] 

您还有其他的替代产品。例如,使用列表理解:

In [126]: [sum(x) for x in zip(*big_list)] 
Out[126]: [6, 12, 18, 24, 30] 
+0

啊,我在想你在哪里。有一段时间没有见过你。一秒钟,我开始担心;-) –

+0

@ChristianDean是的,一直在做一些旅行。希望你不要太想我了:p –

0

您可以将列表存储在列表中并对它们进行求和。

你可能有这样的事情:

list_a = [1,2,3,4,5] 
list_b = [2,4,6,8,10] 
list_c = [3,6,9,12,15] 

list_of_lists = [list_a, list_b, list_c] # this could be 20+ lists 

def sum_lists(): 
    temp_list = [] 

    for index in range(len(list_a)): 
     temp_list.append(sum([l[index] for l in list_of_lists])) 

    return temp_list 

total = sum_lists() 
-1

这是我的选择:

list_a = [1, 2, 3, 4, 5] 
list_b = [2, 4, 6, 8, 10] 
list_c = [3, 6, 9, 12, 15] 

def sum_lists(*arg): 

    return [sum(i) for i in zip(*arg)] 


results = sum_lists(list_a, list_b, list_c) 
+0

这与我的回答有什么不同? –