Say, I have a two 2D list like below:
[[('a', '1'), ('a', '12'), ('a', '3')], [('b', '21'), ('b', '31')], [ ('c', '11')]]
The output I want to achieve is:
Output_list=[['1','12','3'], ['21','31'], ['11']]
The main complexity here is I want to achieve the output through a single list comprehension
.
One of my attempts was:
print [a for innerList in fin_list1 for a,b in innerList]
Output:
['1', '12', '3', '21', '31', '11']
But, as you can see, though I have successfully retrieve the second elements of each tuple, i failed to retain my inner list structure.
We start with this:
>>> l = [[('a', '1'), ('a', '12'), ('a', '3')], [('b', '21'), ('b', '31')], [ ('c', '11')]]
Initially you tried to do something along these lines:
>>> [y for sublist in l for x, y in sublist]
['1', '12', '3', '21', '31', '11']
The mistake here is that this list comprehension is one-dimensional, i.e. all the values will be just integers instead of lists themselves
In order to make this two-dimensional, our values need to be lists. The easiest way to do this is by having our value expression be a nested list comprehension that iterates over the elements of the sublists of the original list:
>>> [[y for x, y in sublist] for sublist in l]
[['1', '12', '3'], ['21', '31'], ['11']]
Technically this is two list comprehensions, but obviously a list comprehension can be replaced by map
as explained in Roberto's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With