如何同时合并两个列表?

问题描述 投票:0回答:2
list1=[a,b,c,d]
list2=[d,e,f,g]

我想要一个 list3 应该是这样的。

list3=[a-d,b-e,c-f,d-g]

请告诉我如何在循环中做这个,因为我的... list1list2 有很多实体.list1和list2都是字符串.例如:list1=[a,b,c,d] list2=[d,e,f,g] 我想要一个list3,它应该是:list3=[a-d,b-e,c-f,d-g]。

list1=['cat','dog']
list2=['dog','cat']
list3=['cat-dog','dog-cat']
python python-3.x list
2个回答
4
投票

有了 zip 你可以把两个列表放在一起,同时对它们进行迭代。

list1=[a,b,c,d]
list2=[d,e,f,g]
list3 = [x-y for x,y in zip(list1,list2)]

EDIT: 我回答的前提是你的列表中只有整数,如果你想对字符串做同样的事情,你可以这样做。

list1 = ["a", "b", "c", "d"]
list2 = ["d", "e", "f", "g"]
list3 = ["-".join([x, y]) for x, y in zip(list1, list2)]

3
投票

如果你的列表可以有不同的长度,就可以使用 zip_longest:

from itertools import zip_longest

list3 = [x-y for x,y in zip_longest(list1,list2, fillvalue=0)]

如果名单的长度相同,它的行为就像通常的一样。zip如果没有,它就会在最短的列表中填入 fillvalue (在本例中为0)来匹配其他元素的长度,而不是忽略剩余的元素。

如果你的列表中包含字符串,你最好使用字符串操作方法并改变 fillvalue。

from itertools import zip_longest

list3 = [str(x) + '-' + str(y) for x,y in zip_longest(list1,list2, fillvalue="")]
© www.soinside.com 2019 - 2024. All rights reserved.