简体   繁体   中英

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=[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. list1 and list2 contain strings. 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.

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 :

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.

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="")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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