python - 按元素查找两个列表列表的总和
问题描述
我有两个列表列表,我想从两个列表元素中找到总和
list1 = [[1, 2, 3], [4, 5, 6]]
list2 = [[10, 2, 3], [11, 5, 6]]
结果应该是[11, 4, 6], [15, 10, 12]
目前,我有
for i in len(list1):
sum = list1[i] + list2[i]
print(sum)
但它给了我错误的结果。
解决方案
你可以zip
像这样使用,
>>> list1
[[1, 2, 3], [4, 5, 6]]
>>> list2
[[10, 2, 3], [11, 5, 6]]
>>> [[x+y for x,y in zip(l1, l2)] for l1,l2 in zip(list1,list2)]
[[11, 4, 6], [15, 10, 12]]
或者如果您不确定,如果两个列表的长度相同,那么您可以使用zip_longest
(izip_longest
在 python2 中) fromitertools
和使用fillvalue
类似的,
>>> import itertools
>>> y = itertools.zip_longest([1,2], [3,4,5], fillvalue=0)
>>> list(y)
[(1, 3), (2, 4), (0, 5)]
然后您可以将其用于大小不等的数据,例如,
>>> from itertools import zip_longest
>>> list1=[[1, 2, 3], [4, 5]]
>>> list2=[[10, 2, 3], [11, 5, 6], [1,2,3]]
>>> [[x+y for x,y in zip_longest(l1, l2, fillvalue=0)] for l1,l2 in zip_longest(list1,list2, fillvalue=[])]
[[11, 4, 6], [15, 10, 6], [1, 2, 3]]
推荐阅读
- python - 如何从多个 url 中抓取数据以保存为单个按日期排序的 csv 文件?
- foreach - 辅助选择器的“ForEach”给了我致命错误:索引超出范围
- c - 如何在 C 中模拟 Python 的 for-else 语句
- python - 我怎样才能让用户改变他自己的形象不仅仅是从管理员
- apache-spark - Spark 数据集中的 Kryo 编码器与 RowEncoder
- java - 如何解决 com.jogamp.common.type.WriteCloneable 的错误类文件未找到
- docker - Docker error can't copy a file after build it
- html - 当全高图像比屏幕宽时如何居中对齐?
- python - 如何在不替换总体的情况下快速创建随机样本?
- python - 我如何让玩家不会从平台方面受到影响