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.
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?
NB: I'm using Python 3.3.
解决方案
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)]
eg
>>> 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]
You can use this trick to make sure a is longer than b
b, a = sorted((a, b), key=len)