简体   繁体   中英

How to interleave elements from two lists in python

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2
print(list3)

output ---

['a', 'b', 'c', 1, 2, 3]

but I want output like this ---

['a',1,'b',2,'c',3]

please help me

You can create a for loop and use zip and extend :

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = []
for items in zip(list1, list2):
    list3.extend(items)

print(list3)

Alternatively a list comprehension (however it is both slower and less readable, still will keep it here just for information as to how to handle cases where an iterable has to be extended in a comprehension)

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = [c for items in zip(list1, list2) for c in items]
print(list3)
from itertools import chain
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

result = list(chain(*zip(list1, list2)))
print(result)

As a [better] alternative (because it will be evaluated lazily), as mentioned by @juanpa.arrivillaga:

result = list(chain.from_iterable(zip(list1, list2)))

A brute-force merge will go something like this:

 list1 = ['a', 'b', 'c'] list2 = [1, 2, 3] list3 = [] ## merge two list with output like ['a',1,'b',2,'c',3] for i in range(len(list1)): list3.append(list1[i]) list3.append(list2[i]) print(list3)

A better way is to use itertool or chain as above!

If the lists of the same length, you can zip the lists and use list.extend method:

new_list = []
for i,j in zip(list1,list2):
    new_list.extend([i,j])
print(new_list)

Output:

['a', 1, 'b', 2, 'c', 3]

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