简体   繁体   中英

Shuffle two python list

I am having issue figuring out a way to shuffle two python list. I have two different lists.

first = [1,2,3]
second = [4,5,6]

I want my final list to be a combination of these two lists but shuffled in a particular way.

combined = [1,4,2,5,3,6]

I can shuffle both the lists and combine them, but the result would be [2,1,3,6,5,4] but what I want is [1,4,2,5,3,6] .

The combined list should have one item from the first list, and then the subsequent item from the second list.

The two lists might even be of different lengths.

first = [1,2,3]
second = [4,5,6,7]

def shuffle(f, s):
    newlist = []
    maxlen = len(f) if len(f) > len(s) else len(s)
    for i in range(maxlen):
        try:
            newlist.append(f[i])
        except IndexError:
            pass
        try:
            newlist.append(s[i])
        except IndexError:
            pass
    return newlist

print(shuffle(first, second))

If both lists are always going to be the same length then you could do:

x = [1, 2, 3]
y = [4, 5, 6]

z = []

for i in range(len(x)):# Could be in range of y too as they would be the same length
    z.append(x[i])
    z.append(y[i])

If they are different lengths then you will have to do things slightly differently and check which one is longer and make that the one you get the length of. The you will need to check each iteration of the loop if you are past the length of the shorter one.

Purely because I want to understand itertools one day:

from itertools import chain, zip_longest, filterfalse

first = [1, 2, 3]
second = [4, 5, 6, 9, 10, 11]

result = filterfalse(
    lambda x: x is None,
    chain.from_iterable(zip_longest(first, second)))

print(tuple(result))

Enjoy!

For lists of unequal length, use itertools.zip_longest :

from itertools import chain, zip_longest

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

combined = [x for x in chain(*zip_longest(a, b)) if x is not None]
print(combined)  # -> [1, 4, 2, 5, 3, 6, 7]

For Python 2, replace zip_longest with izip_longest .

This is based on pylang 's answer on Interleave multiple lists of the same length in Python


Here it is generalized, as a function in a module.

#!/usr/bin/env python3

from itertools import chain, zip_longest


def interleave(*args):
    """
    Interleave iterables.

    >>> list(interleave([1, 2, 3], [4, 5, 6, 7]))
    [1, 4, 2, 5, 3, 6, 7]
    >>> ''.join(interleave('abc', 'def', 'ghi'))
    'adgbehcfi'
    """
    for x in chain(*zip_longest(*args)):
        if x is not None:
            yield x

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