如何在python中优雅地交织长度不均匀的两个列表? [英] How to elegantly interleave two lists of uneven length in python?
问题描述
我想在python中合并两个列表,列表的长度不同,以便较短列表的元素在最终列表中的间距尽可能相等.即我想使用[1, 2, 3, 4]
和['a','b']
并将它们合并以获得类似于[1, 'a', 2, 3, 'b', 4]
的列表.它也需要能够使用不是精确倍数的列表,因此它可能需要[1, 2, 3, 4, 5]
和['a', 'b', 'c']
并产生[1, 'a', 2, 'b', 3, 'c', 4, 5]
或类似的结果.它需要保留两个列表的顺序.
I want to merge two lists in python, with the lists being of different lengths, so that the elements of the shorter list are as equally spaced within the final list as possible. i.e. I want to take [1, 2, 3, 4]
and ['a','b']
and merge them to get a list similar to [1, 'a', 2, 3, 'b', 4]
. It needs to be able to function with lists that aren't exact multiples too, so it could take [1, 2, 3, 4, 5]
and ['a', 'b', 'c']
and produce [1, 'a', 2, 'b', 3, 'c', 4, 5]
or similar. It needs to preserve the ordering of both lists.
我可以看到如何通过一种强力的蛮力方法来做到这一点,但是由于Python似乎拥有大量出色的工具,可以完成我不知道的各种聪明的事情(至今),所以我想知道是否还有什么我可以使用的优雅的东西?
I can see how to do this by a long-winded brute force method but since Python seems to have a vast array of excellent tools to do all sorts of clever things which I don't know about (yet) I wondered whether there's anything more elegant I can use?
注意:我正在使用Python 3.3.
NB: I'm using Python 3.3.
推荐答案
如果a
是较长的列表,而b
是较短的列表
if a
is the longer list and b
is the shorter
from itertools import groupby
len_ab = len(a) + len(b)
groups = groupby(((a[len(a)*i//len_ab], b[len(b)*i//len_ab]) for i in range(len_ab)),
key=lambda x:x[0])
[j[i] for k,g in groups for i,j in enumerate(g)]
例如
>>> a = range(8)
>>> b = list("abc")
>>> len_ab = len(a) + len(b)
>>> groups = groupby(((a[len(a)*i//len_ab], b[len(b)*i//len_ab]) for i in range(len_ab)), key=lambda x:x[0])
>>> [j[i] for k,g in groups for i,j in enumerate(g)]
[0, 'a', 1, 2, 'b', 3, 4, 5, 'c', 6, 7]
您可以使用此技巧来确保a
长于b
You can use this trick to make sure a
is longer than b
b, a = sorted((a, b), key=len)
这篇关于如何在python中优雅地交织长度不均匀的两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!