洗牌两个python列表

洗牌两个python列表,python,Python,我在想办法洗牌两个python列表时遇到了问题。 我有两个不同的清单 first = [1,2,3] second = [4,5,6] 我希望我的最终列表是这两个列表的组合,但是以一种特殊的方式被洗牌 combined = [1,4,2,5,3,6] 我可以洗牌两个列表并合并它们,但结果将是[2,1,3,6,5,4],但我想要的是[1,4,2,5,3,6] 组合列表应包含第一个列表中的一个项目,然后是第二个列表中的后续项目 这两个列表甚至可能有不同的长度 如果两个列表的长度始终相同,则可以执

我在想办法洗牌两个python列表时遇到了问题。 我有两个不同的清单

first = [1,2,3]
second = [4,5,6]
我希望我的最终列表是这两个列表的组合,但是以一种特殊的方式被洗牌

combined = [1,4,2,5,3,6]
我可以洗牌两个列表并合并它们,但结果将是
[2,1,3,6,5,4]
,但我想要的是
[1,4,2,5,3,6]

组合列表应包含第一个列表中的一个项目,然后是第二个列表中的后续项目


这两个列表甚至可能有不同的长度

如果两个列表的长度始终相同,则可以执行以下操作:

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

如果它们的长度不同,那么你必须做一些稍微不同的事情,检查哪一个更长,并使其成为你得到的长度。如果超过了较短循环的长度,则需要检查循环的每个迭代。

纯粹是因为我想有一天了解itertools:

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))
来自itertools导入链,邮编最长,filterfalse
第一个=[1,2,3]
秒=[4,5,6,9,10,11]
结果=filterfalse(
lambda x:x是无,
链。从\u iterable(拉链\u最长(第一,第二)))
打印(元组(结果))

享受吧

对于长度不等的列表,请使用:

对于Python 2,将
zip\u longest
替换为

这是基于的


在这里,它是广义的,作为一个模块中的函数

#!/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

这不是一个完全的重复,而是在洗牌之后,列表。这给了我
[4,1,5,2,6,3,7]
,而不是
[1,4,2,5,3,6]
#!/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