在每个x位置合并2个列表

Kin*_*gFu 4 python

假设我有两个列表比另一个更长,x = [1,2,3,4,5,6,7,8]并且y = [a,b,c]我想将y中的每个元素合并到x中的每个第3个索引,因此结果列表z看起来像:z = [1,2,a,3,4,b,5,6,c,7,8]

在python中进行此操作的最佳方法是什么?

And*_*ark 5

以下是itertools文档中的roundrobin配方的改编版本,可以执行您想要的操作:

from itertools import cycle, islice

def merge(a, b, pos):
    "merge('ABCDEF', [1,2,3], 3) --> A B 1 C D 2 E F 3"
    iterables = [iter(a)]*(pos-1) + [iter(b)]
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))
Run Code Online (Sandbox Code Playgroud)

例:

>>> list(merge(xrange(1, 9), 'abc', 3))   # note that this works for any iterable!
[1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8]
Run Code Online (Sandbox Code Playgroud)

或者这里是你可以如何使用roundrobin()它没有任何修改:

>>> x = [1,2,3,4,5,6,7,8]
>>> y = ['a','b','c']
>>> list(roundrobin(*([iter(x)]*2 + [y])))
[1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8]
Run Code Online (Sandbox Code Playgroud)

或者等效但稍微可读的版本:

>>> xiter = iter(x)
>>> list(roundrobin(xiter, xiter, y))
[1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8]
Run Code Online (Sandbox Code Playgroud)

请注意,这两种方法都适用于任何可迭代的,而不仅仅是序列.

这是最初的roundrobin()实现:

from itertools import cycle, islice

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))
Run Code Online (Sandbox Code Playgroud)