在Python中交叉列表

bea*_*605 22 python list

我有两个清单:
[a, b, c] [d, e, f]
我想:
[a, d, b, e, c, f]

在Python中执行此操作的简单方法是什么?

And*_*ark 33

这是一个使用列表理解的非常直接的方法:

>>> lists = [['a', 'b', 'c'], ['d', 'e', 'f']]
>>> [x for t in zip(*lists) for x in t]
['a', 'd', 'b', 'e', 'c', 'f']
Run Code Online (Sandbox Code Playgroud)

或者,如果您将列表作为单独的变量(如在其他答案中):

[x for t in zip(list_a, list_b) for x in t]
Run Code Online (Sandbox Code Playgroud)

  • +1,但与Sven Marnach的答案一样,可能值得解释它的工作原理:压缩列表,然后将结果展平。因为对于大多数新用户而言,“ [[x for t in l in l for x in t]]”的意思是“扁平化l”,这并不直观。 (2认同)
  • 也许只是我的偏好,但这个答案对我来说似乎不那么复杂。 (2认同)

Sve*_*ach 29

一种选择是使用的组合chain.from_iterable()zip():

# Python 3:
from itertools import chain
list(chain.from_iterable(zip(list_a, list_b)))

# Python 2:
from itertools import chain, izip
list(chain.from_iterable(izip(list_a, list_b)))
Run Code Online (Sandbox Code Playgroud)

编辑:正如sr2222在评论中所指出的,如果列表具有不同的长度,这不会很好.在这种情况下,根据所需的语义,您可能希望使用文档roundrobin()配方部分中的 (更常见的)函数itertools:

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)

  • +1.可能是最好的解决方案.但是可能值得解释为什么这样做:压缩给出[(a,d),(b,e),(c,f)],然后链接变平成[a,d,b,e,c,f ].(鼓励人们学习itertools总是一件好事.) (6认同)
  • 如果列表不相等,或者长度至少为+/- 1,这会不会很好? (2认同)