Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Interleave two or more lists
from itertools import chain
import perfplot
def cs1(l):
def _cs1(l):
for i, x in enumerate(l, 1):
yield x
yield f'{x}_{i}'
return list(_cs1(l))
def cs2(l):
out_l = [None] * (len(l) * 2)
out_l[::2] = l
out_l[1::2] = [f'{x}_{i}' for i, x in enumerate(l, 1)]
return out_l
def cs3(l):
return list(chain.from_iterable(
zip(l, [f'{x}_{i}' for i, x in enumerate(l, 1)])))
def ajax(l):
return [
i for b in [[a, '{}_{}'.format(a, i)]
for i, a in enumerate(l, start=1)]
for i in b
def ajax_cs0(l):
# suggested improvement to ajax solution
return [j for i, a in enumerate(l, 1) for j in [a, '{}_{}'.format(a, i)]]
def chrisz(l):
return [
for pair in zip(l, [f'{k}_{j+1}' for j, k in enumerate(l)])
for val in pair
kernels = [cs1, cs2, cs3, ajax_cs0, ajax, chrisz]
setup=lambda c: list('abcd') * c,
labels=[f.__name__ for f in kernels],
n_range=[2**k for k in range(0, 15)],
equality_check=lambda x, y: x == y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment