Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve two separate list of lists from a single list of lists of tuple with list comprehension?

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.

like image 393
Ahsanul Haque Avatar asked Feb 08 '23 16:02

Ahsanul Haque


1 Answers

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.

like image 187
Shashank Avatar answered Feb 15 '23 10:02

Shashank