12

对两个或多个列表求和的最佳方法是什么,即使它们的长度不同?

例如我有:

lists = [[1, 2], [0, 3, 4], [5]]

结果应该是:

result = [6, 5, 4]
4

4 回答 4

19

您可以使用itertools.izip_longest(), 并使用fillvalue等于0

In [6]: [sum(x) for x in itertools.izip_longest(*lists, fillvalue=0)]
Out[6]: [6, 5, 4]

对于 Python < 2.6:

In [27]: ml = max(map(len, lists))

In [28]: ml       #length of the longest list in lists
Out[28]: 3

In [29]: [sum(x) for x in zip(*map(lambda x:x+[0]*ml if len(x)<ml else x, lists))]
Out[29]: [6, 5, 4]
于 2012-10-22T12:27:07.563 回答
1
#You can do the same without using predefined header files.
def sumlists(a,b,c):
    sumlist = []
    while(len(a)!=len(b) or len(a)!=len(c)):
        if len(a)>len(b):
            b.append(0)
        if len(a)>len(c):
            c.append(0)
        elif len(b)>len(a):
            a.append(0)
        if len(b)>len(c):
             c.append(0)
        elif len(c)>len(a):
            a.append(0)
        if len(c)>len(b):
             b.append(0)
    for i,j,k in zip(a,b,c):
         sumlist.append(i+j+k)
    return sumlist
 print(sumlists([1,2],[0,3,4],[5]))
于 2019-07-19T09:22:17.890 回答
0

我想出的最好的方法如下:

result = [sum(filter(None, i)) for i in map(None, *lists)]

这还不错,但我必须添加 NoneTypes 然后过滤它们才能总结。

于 2015-05-04T17:16:29.397 回答
0

这适用于具有一千个元素的列表。检查 if 语句要附加的天气需要很长时间,但这运行得非常快。我有一个函数,“longestlist”,它识别并返回最长的列表,但这很容易编写,所以使用该输出......

def listfiller(a,b,c,d)
  longest = longestlist(a,b,c,d)
  for i in range(len(longest)-len(a)):
    a.append(0)
  for i in range(len(longest)-len(b)):
    b.append(0)
    print(b)
  for i in range(len(longest)-len(c)):
    c.append(0)
  for i in range(len(longest)-len(d)):
    d.append(0)
  return(a,b,c,d)
于 2021-04-19T08:50:06.470 回答