2. How do I make a flat checklist out of an inventory of lists?
The next drawing illustrates what’s being requested on this query:
You are able to do this conversion by utilizing a list comprehension as follows:
# utilizing checklist comprehension
mylist = [
[1, 5, 3],
[4, 2, 1],
[5, 6]
]myflatlist = [item for sublist in mylist for item in sublist]
print(myflatlist)
# output
[1, 5, 3, 4, 2, 1, 5, 6]
The checklist comprehension above will also be written as nested for loops. It’s extra intuitive and simpler to grasp however checklist comprehension is extra performant particularly when working with giant lists.
# utilizing for loops
mylist = [
[1, 5, 3],
[4, 2, 1],
[5, 6]
]myflatlist = []
for sublist in mylist:
for merchandise in sublist:
myflatlist.append(merchandise)
print(myflatlist)
# output
[1, 5, 3, 4, 2, 1, 5, 6]
If you happen to’re utilizing Pandas, the explode
operate makes this flattening operation fairly straightforward however it’s essential convert the checklist to a Pandas sequence first. In order for you the ultimate output to be an inventory, then you possibly can convert the output of the explode
operate to an inventory utilizing the checklist constructor.
# utilizing the explode operate
import pandas as pdmyflatlist = checklist(pd.Sequence(mylist).explode())
print(myflatlist)
# output
[1, 5, 3, 4, 2, 1, 5, 6]