简体   繁体   中英

Python two list lists shuffle

I have two list:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]

I need to get something like this:

c = [1, 5, 2, 6, 3, 7, 4, 8]

I use this solution:

c = list(reduce(lambda x, y: x + y, zip(a, b)))

Is there a better way to do this?

Using List Comprehension :

>>> [x for tup in zip(a, b) for x in tup]
[1, 5, 2, 6, 3, 7, 4, 8]

The above nested list comprehension is equivalent to following nested for loops (Just in case you get confused):

result = []
for tup in zip(a, b):
    for x in tup:
        result.append(x)

Using chain :

from itertools import chain, izip
interweaved = list(chain.from_iterable(izip(a, b)))
# [1, 5, 2, 6, 3, 7, 4, 8]

也可行:

list(sum(zip(a, b), ()))

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