将两个 LISTS 值的 SUM 添加到新 LIST
Posted
技术标签:
【中文标题】将两个 LISTS 值的 SUM 添加到新 LIST【英文标题】:Add SUM of values of two LISTS into new LIST 【发布时间】:2012-12-12 14:46:50 【问题描述】:我有以下两个列表:
first = [1,2,3,4,5]
second = [6,7,8,9,10]
现在我想将这两个列表中的项目添加到一个新列表中。
输出应该是
third = [7,9,11,13,15]
【问题讨论】:
【参考方案1】:zip
函数在这里很有用,与列表推导一起使用。
[x + y for x, y in zip(first, second)]
如果您有一个列表列表(而不仅仅是两个列表):
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]
【讨论】:
只是好奇如果数组长度不同,zip() 将如何处理?即 zip 为不同的数组长度返回什么以及这将如何影响 x + y 的操作 @ealeon:当最短的迭代用完时,“压缩”停止。因此,如果first
的长度为 10,second
的长度为 6,则压缩迭代的结果将是长度 6。
我认为它比其他答案更有用,因为您可以做一些有用的事情,例如取平均值或对数组中的每个元素赋予不同的权重并将它们组合起来
在不知道列表数量的情况下有没有办法做到这一点?
@traggatmot: >>> lists_of_lists = [[1, 2, 3], [4, 5, 6]]
>>> [sum(x) for x in zip(*lists_of_lists)]
[5, 7, 9]
【参考方案2】:
来自docs
import operator
list(map(operator.add, first,second))
【讨论】:
你的意思是:list(map(operator.add, first,second))【参考方案3】:numpy.add
(numpy.subtract
等)中的默认行为是元素方面的:
import numpy as np
np.add(first, second)
哪个输出
array([7,9,11,13,15])
【讨论】:
迄今为止最好的答案 它应该可以工作,但在我的实验中它没有......我不知道为什么,但 numpy 在我看来是一个强大的库以及一个复杂的库...... @decadenza 你是怎么做这个实验的? 嗨@Ashfaq,几个月过去了,我对 Numpy 库有了更好的了解。我在 np.array 定义中错了。对不起。 使用 np.add(first, second).tolist() 获取列表中的结果【参考方案4】:假设a
和b
两个列表的长度相同,则不需要 zip、numpy 或其他任何东西。
Python 2.x 和 3.x:
[a[i]+b[i] for i in range(len(a))]
【讨论】:
这看起来不错,如果我们必须计算超过 2 个列表的结果总和列表【参考方案5】:这将自身扩展到任意数量的列表:
[sum(sublist) for sublist in itertools.izip(*myListOfLists)]
在您的情况下,myListOfLists
将是 [first, second]
【讨论】:
你确定izip.from_iterable
?
@DSM:该死!我想我在想chain
。更新【参考方案6】:
试试下面的代码:
first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))
【讨论】:
+1 用于这个紧凑且不言自明的解决方案。值得注意的是,这也适用于 2 个以上的列表:map(sum, zip(first, second, third, fourth, ...))
【参考方案7】:
简单快捷的方法是:
three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]
或者,您可以使用 numpy sum:
from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])
【讨论】:
这很好地概括了更长的列表,这正是我所需要的!【参考方案8】:first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
three = list(map(sum, first, second))
print(three)
# Output
[7, 9, 11, 13, 15]
【讨论】:
lambda x, y: x + y
可以简单地为sum
。【参考方案9】:
单线解决方案
list(map(lambda x,y: x+y, a,b))
【讨论】:
【参考方案10】:如果你有未知数量的相同长度的列表,你可以使用下面的函数。
这里的 *args 接受可变数量的列表参数(但每个参数的总和数量相同)。 * 再次用于解包每个列表中的元素。
def sum_lists(*args):
return list(map(sum, zip(*args)))
a = [1,2,3]
b = [1,2,3]
sum_lists(a,b)
输出:
[2, 4, 6]
或者有 3 个列表
sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])
输出:
[19, 19, 19, 19, 19]
【讨论】:
【参考方案11】:我的回答与 3 月 17 日 9:25 回答的 Thiru 重复。
更简单快捷,以下是他的解决方案:
简单快捷的方法是:
three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]
或者,您可以使用 numpy sum:
from numpy import sum three = sum([first,second], axis=0) # array([7,9,11,13,15])
你需要 numpy!
numpy 数组可以做一些像向量这样的操作import numpy as np
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = list(np.array(a) + np.array(b))
print c
# [7, 9, 11, 13, 15]
【讨论】:
您不需要 numpy 来对两个列表中的成对元素求和。【参考方案12】:如果您有不同长度的列表怎么办,
那么你可以尝试这样的事情(使用zip_longest
)
from itertools import zip_longest # izip_longest for python2.x
l1 = [1, 2, 3]
l2 = [4, 5, 6, 7]
>>> list(map(sum, zip_longest(l1, l2, fillvalue=0)))
[5, 7, 9, 7]
【讨论】:
【参考方案13】:您可以使用zip()
,它将两个数组“交错”在一起,然后使用map()
,它将一个函数应用于一个可迭代对象中的每个元素:
>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> zip(a, b)
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> map(lambda x: x[0] + x[1], zip(a, b))
[7, 9, 11, 13, 15]
【讨论】:
【参考方案14】:这是另一种方法。我们利用python内部的__add__函数:
class SumList(object):
def __init__(self, this_list):
self.mylist = this_list
def __add__(self, other):
new_list = []
zipped_list = zip(self.mylist, other.mylist)
for item in zipped_list:
new_list.append(item[0] + item[1])
return SumList(new_list)
def __repr__(self):
return str(self.mylist)
list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)
输出
[11, 22, 33, 44, 55]
【讨论】:
【参考方案15】:如果您还想添加列表中的其余值,您可以使用它(这适用于 Python3.5)
def addVectors(v1, v2):
sum = [x + y for x, y in zip(v1, v2)]
if not len(v1) >= len(v2):
sum += v2[len(v1):]
else:
sum += v1[len(v2):]
return sum
#for testing
if __name__=='__main__':
a = [1, 2]
b = [1, 2, 3, 4]
print(a)
print(b)
print(addVectors(a,b))
【讨论】:
【参考方案16】: first = [1,2,3,4,5]
second = [6,7,8,9,10]
#one way
third = [x + y for x, y in zip(first, second)]
print("third" , third)
#otherway
fourth = []
for i,j in zip(first,second):
global fourth
fourth.append(i + j)
print("fourth" , fourth )
#third [7, 9, 11, 13, 15]
#fourth [7, 9, 11, 13, 15]
【讨论】:
【参考方案17】:这是另一种方法。它对我来说很好用。
N=int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))
sum=[]
for i in range(0,N):
sum.append(num1[i]+num2[i])
for element in sum:
print(element, end=" ")
print("")
【讨论】:
【参考方案18】:j = min(len(l1), len(l2))
l3 = [l1[i]+l2[i] for i in range(j)]
【讨论】:
虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。【参考方案19】:如果您将列表视为 numpy 数组,那么您需要轻松地对它们求和:
import numpy as np
third = np.array(first) + np.array(second)
print third
[7, 9, 11, 13, 15]
【讨论】:
【参考方案20】:也许是最简单的方法:
first = [1,2,3,4,5]
second = [6,7,8,9,10]
three=[]
for i in range(0,5):
three.append(first[i]+second[i])
print(three)
【讨论】:
【参考方案21】:您可以使用此方法,但仅当两个列表大小相同时才有效:
first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
third = []
a = len(first)
b = int(0)
while True:
x = first[b]
y = second[b]
ans = x + y
third.append(ans)
b = b + 1
if b == a:
break
print third
【讨论】:
以上是关于将两个 LISTS 值的 SUM 添加到新 LIST的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 599. Minimum Index Sum of Two Lists (从两个lists里找到相同的并且位置总和最靠前的)
599. Minimum Index Sum of Two Lists两个餐厅列表的索引和最小