在 Python 中交错多个相同长度的列表 [英] Interleave multiple lists of the same length in Python
本文介绍了在 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]
其中 l1
和 l2
是两个列表.
where l1
and l2
are the two lists.
如果有 N 个列表要交错,则
If there are N lists to interleave, then
lists = [l1, l2, ...]
[val for tup in zip(*lists) for val in tup]
这篇关于在 Python 中交错多个相同长度的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文