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

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

问题描述

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

I have two lists:
[a, b, c] [d, e, f]
I want:
[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() 食谱中的功能 的部分 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天全站免登陆