在Python中交织多个相同长度的列表 [英] Interleave multiple lists of the same length in Python

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

问题描述

在Python中,有没有一种好的方法来插入两个相同长度的列表?

In Python, is there a good way to interleave two lists of the same length?

说我得到了[1,2,3][10,20,30].我想将它们转换为[1,10,2,20,3,30].

Say I'm given [1,2,3] and [10,20,30]. I'd like to transform those into [1,10,2,20,3,30].

推荐答案

发布问题后,我意识到我可以简单地执行以下操作:

Having posted the question, I've realised that I can simply do the following:

[val for pair in zip(l1, l2) for val in pair]

其中l1l2是两个列表.

如果要插入N个列表,则

If there are N lists to interleave, then

lists = [l1, l2, ...]
[val for tup in zip(*lists) for val in tup]

有关更多食谱,请遵循插入列表后缀值的最佳方法.那里展示的某些方法可以推广到两个或更多相等长度的列表.

For more recipes, follow Best way to interleave a list with its suffix values. Some of the methods demonstrated there can be generalised to two or more lists of equal length.

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

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