Python 中的交错列表 [英] Interleaving Lists in Python

查看:28
本文介绍了Python 中的交错列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:
[a, b, c] [d, e, f]
我要:
[a, d, b, e, c, f]

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

What's a simple way to do this in Python?

推荐答案

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

One option is to use a combination of chain.from_iterable() and 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)))

编辑:正如 sr2222 在评论中指出的那样,这不起作用好吧,如果列表有不同的长度.在这种情况下,取决于所需的语义,您可能想要使用(更通用的)roundrobin()来自 recipe 的函数部分itertools 文档:

Edit: As pointed out by sr2222 in the comments, this does not work well if the lists have different lengths. In that case, depending on the desired semantics, you might want to use the (far more general) roundrobin() function from the recipe section of the itertools documentation:

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

这篇关于Python 中的交错列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆