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 possi
A variant of @Jon Clements answer using more_itertools.collate with explanation.
Given
import itertools as it
import more_itertools as mit
a, b = range(1, 5), ["a", "b"]
Code
first = enumerate(a)
second = zip(it.count(0, len(a) // len(b)), b)
[x for i, x in mit.collate(first, second, key=lambda x: x[0])]
# [1, 'a', 2, 3, 'b', 4]
Details
This answer is updated to use with Python 3.
first
and second
are iterables of tuples, each tuple comprising a position-element pair.
list(first)
# [(0, 1), (1, 2), (2, 3), (3, 4)]
list(second)
# [(0, 'a'), (2, 'b')]
more_itertools.collate()
wraps heapq.merge(), which merges the pre-sorted first
and second
iterables in order. In the final list comprehension, the key
is the sorting function while the last element in each tuple in returned.
Install this third-party package via > pip install more_itertools
or use heapq.merge() directly.