简体   繁体   English

如何同时合并两个列表?

[英]How to merge two lists simultaneously?

list1=[a,b,c,d]
list2=[d,e,f,g]

I want a list3 which should look like:我想要一个应该如下所示的list3

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

Please tell me how to do this in a loop as my list1 and list2 have many entities.请告诉我如何循环执行此操作,因为我的list1list2有很多实体。 list1 and list2 contain strings. list1 和 list2 包含字符串。 For example:例如:

list1=['cat','dog']
list2=['dog','cat']
list3=['cat-dog','dog-cat']

With zip you can put two lists together and iterate over them simultaneously.使用zip ,您可以将两个列表放在一起并同时迭代它们。

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

EDIT: I answered with the preassumption that you had only integers in your list, if you want to do the same for strings you can do this:编辑:我假设你的列表中只有整数,如果你想对字符串做同样的事情,你可以这样做:

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

If your lists can be of different lengths, use zip_longest :如果您的列表可以有不同的长度,请使用zip_longest

from itertools import zip_longest

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

If the lists have the same length, it behaves like the usual zip , if not, it fills the shortest list with fillvalue (in this case zeros) to match the length of the other, instead of ignoring the remaining elements.如果列表具有相同的长度,它的行为就像通常的zip ,如果不是,它用填充fillvalue (在本例中为零)填充最短列表以匹配另一个的长度,而不是忽略剩余的元素。

If your list contains strings, you're better off using string manipulation methods and changing the fillvalue.如果您的列表包含字符串,则最好使用字符串操作方法并更改填充值。

from itertools import zip_longest

list3 = [str(x) + '-' + str(y) for x,y in zip_longest(list1,list2, fillvalue="")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM