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]
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 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))
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)
How to force three lists to have the same length in Python 3.7?
You could use these functions:
def padlist(lst, size, defvalue=None):
if len(lst) < size:
lst.extend([defvalue] * (size - len(lst)))
def padlists(lsts, defvalue=None):
size = max(len(lst) for lst in lsts)
for lst in lsts:
padlist(lst, size, defvalue)
# Demo
lsts = [
["a", "b", "c"],
["a", "b", "c", "d", "e"],
["a", "b"],
]
padlists(lsts, "") # provide the value to pad with
print(lsts) # shorter lists are padded with blanks
How to interleave two lists by chunks
What about this:
A = [1.1, 1.1, 1.1, 1.1, 1.2, 1.2, 1.2, 1.2, 1.3, 1.3]
B = [2.1, 2.1, 2.1, 2.1, 2.2, 2.2, 2.2, 2.2, 2.3, 2.3]
sep = 4
num = len(A)
iterations = int(num / sep) + 1
merged = []
for i in range(iterations):
start = sep * i
end = sep * (i + 1)
merged.extend(A[start:end])
merged.extend(B[start:end])
print(merged)
>>> '[1.1, 1.1, 1.1, 1.1, 2.1, 2.1, 2.1, 2.1, 1.2, 1.2, 1.2, 1.2, 2.2, 2.2, 2.2, 2.2, 1.3, 1.3, 2.3, 2.3]'
Writing multiple lists of different lengths to same rows in Python with each list into a single cell
You can convert data to dictionary and append()
to existing DataFrame
It will need to convert list [1, 2, 3]
(and similar) to string "1,2,3"
(etc.)
import pandas as pd
df = pd.DataFrame(columns=['Name', 'Date', 'Patcit', 'Npatcit', 'Class'])
# -------------------------------
Name = ['Jon']
Date = [1985]
Patcit = [1, 2, 3]
Npatcit = [4, 5, 6, 7, 8]
Class = [9, 10]
row = {
'Name': Name[0],
'Date': Date[0],
'Patcit': ','.join(str(x) for x in Patcit),
'Npatcit': ','.join(str(x) for x in Npatcit),
'Class': ','.join(str(x) for x in Class),
}
df = df.append(row, ignore_index=True)
#print(df)
# -------------------------------
Name = ['Nikhil']
Date = [1988]
Patcit = [1, 2, 3]
Npatcit = [4, 5, 6, 7]
Class = [9, 10, 11, 12, 13]
row = {
'Name': Name[0],
'Date': Date[0],
'Patcit': ','.join(str(x) for x in Patcit),
'Npatcit': ','.join(str(x) for x in Npatcit),
'Class': ','.join(str(x) for x in Class),
}
df = df.append(row, ignore_index=True)
print(df)
Result
Name Date Patcit Npatcit Class
0 Jon 1985 1,2,3 4,5,6,7,8 9,10
1 Nikhil 1988 1,2,3 4,5,6,7 9,10,11,12,13
And later you can write to csv using standard separator - comma - or other separator.
df.to_csv('output.csv', sep=';')
Or see other question which describes how to write fixed-width-file
Related Topics
Tensorflow Install Fails with "Compiletime Version 3.5 of Module Does Not Match Runtime Version 3.6"
Tutorial or Guide for Scripting Xcode Build Phases
Running a Bash Script from Python
Usb Automatic Detection in Python for Linux Env
Checking Running Python Script Within the Python Script
Passing Variable from Python Script to Bash Script
Use Df Command to Show Only the %Used
Fastest Way to Download 3 Million Objects from a S3 Bucket
How to Run Celery Workers by Superuser
Make (Install from Source) Python Without Running Tests
Creating a Symbolic in Shared Volume of Docker and Accessing It in Host MAChine
Disable Webcam's Autofocus in Linux
How to Capture Mouseevents and Keyevents Using Python in Background on Linux
I Have a Problem with Sending Mail:Typeerror: _Init_() Got an Unexpected Keyword Argument 'Context'
How to Install Writable Shared and User Specific Data Files with Setuptools