Interleave multiple lists of the same length in Python
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]
where l1
and l2
are the two lists.
If there are N lists to interleave, then
lists = [l1, l2, ...]
[val for tup in zip(*lists) for val in tup]
How to interleave two lists of different length?
def twolists(list1, list2):
newlist = []
a1 = len(list1)
a2 = len(list2)
for i in range(max(a1, a2)):
if i < a1:
newlist.append(list1[i])
if i < a2:
newlist.append(list2[i])
return newlist
Interleaving Lists in Python
One option is to use a combination of chain.from_iterable()
and zip()
:
# Python 3:
from itertools import chain
list(chain.from_iterable(zip(list_a, list_b)))
# Python 2:
from itertools import chain, izip
list(chain.from_iterable(izip(list_a, list_b)))
Edit: As pointed out by sr2222 in the comments, this does not work
well if the lists have different lengths. In that case, depending on
the desired semantics, you might want to use the (far more general) roundrobin()
function from the recipe
section of theitertools
documentation:
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
Interleave 4 lists of same length python
Provided the lists are the same length, zip()
can be used to interleave four lists just like it was used for interleaving two in the question you linked:
>>> l1 = ["a", "b", "c", "d"]
>>> l2 = [1, 2, 3, 4]
>>> l3 = ["w", "x", "y", "z"]
>>> l4 = [5, 6, 7, 8]
>>> l5 = [x for y in zip(l1, l2, l3, l4) for x in y]
>>> l5
['a', 1, 'w', 5, 'b', 2, 'x', 6, 'c', 3, 'y', 7, 'd', 4, 'z', 8]
Interleave multiple lists of variable-length in Python3
Looks like you need itertools.zip_longest
from itertools import zip_longest
l1=[1,2,3]
l2=[10,20,30]
l3=[101,102,103,104]
print([y for x in zip_longest(l1,l2,l3, fillvalue=None) for y in x if y is not None])
Output:
[1, 10, 101, 2, 20, 102, 3, 30, 103, 104]
How to elegantly interleave two lists of uneven length in python?
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)
Related Topics
What Do I Use for a Max-Heap Implementation in Python
Typeerror: Module._Init_() Takes at Most 2 Arguments (3 Given)
Solving "Dll Load Failed: %1 Is Not a Valid Win32 Application." for Pygame
Count Number of Non-Nan Entries in Each Column of Spark Dataframe with Pyspark
Extract Subset of Key-Value Pairs from Dictionary
How to Make Urllib2 Requests Through Tor in Python
Two Values from One Input in Python
How to Convert List of Key-Value Tuples into Dictionary
How to Use Brew Installed Python as the Default Python
Named Regular Expression Group "(P<Group_Name>Regexp)": What Does "P" Stand For
Pandas Fill Missing Values in Dataframe from Another Dataframe
Strange Behavior of Lists in Python
Implementation Hmac-Sha1 in Python
How to Change the Figure Size with Subplots
Python: Download a File from an Ftp Server