Reputation: 2655
I have a structure of the form:
lst= [[['A'], ['B'], ['C']], [['A'], ['B'], ['D'], ['E']], [['B'], ['C']]]
I want to collapse the innermost layers of the lists such that I get the following structure:
lst= [['A', 'B', 'C'], ['A', 'B', 'D', 'E'], ['B', 'C']]
I have tried to flatten the list by doing:
[item for sublst in lst for item in sublst]
But this collapses all layers instead to a one dimensional list.
What is the most pythonic way to address this?
Upvotes: 1
Views: 954
Reputation: 26039
You need to iterate over sublists and index them to get desired output (but this assumes your inner list holds only one element):
lst= [[['A'], ['B'], ['C']], [['A'], ['B'], ['D'], ['E']], [['B'], ['C']]]
result = [[y[0] for y in x] for x in lst]
# [['A', 'B', 'C'], ['A', 'B', 'D', 'E'], ['B', 'C']]
Optionally, you can use chain.from_iterable
from itertools
(Now this handles any number of elements in inner lists):
from itertools import chain
lst= [[['A'], ['B'], ['C']], [['A'], ['B'], ['D'], ['E']], [['B'], ['C']]]
result = [list(chain.from_iterable(x)) for x in lst]
Upvotes: 1
Reputation: 1122292
You need to flatten the elements of lst
, not lst
itself.
So use the double loop list comprehension inside another list comprehension, where the outer comprehension iterates over your top-level list:
[[item for inner in sublst for item in inner] for sublst in lst]
Since your inner-most lists each only contain a single element, you could also use indexing to get those values:
[[inner[0] for inner in sublst] for sublst in lst]
Demo:
>>> lst = [[['A'], ['B'], ['C']], [['A'], ['B'], ['D'], ['E']], [['B'], ['C']]]
>>> [[item for inner in sublst for item in inner] for sublst in lst]
[['A', 'B', 'C'], ['A', 'B', 'D', 'E'], ['B', 'C']]
>>> [[inner[0] for inner in sublst] for sublst in lst]
[['A', 'B', 'C'], ['A', 'B', 'D', 'E'], ['B', 'C']]
Upvotes: 2