How to get two separate list of lists from one list of lists of tuples with a list?

Let's say I have two 2D lists, as shown 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 difficulty here is that I want to achieve the result with one list comprehension.

One of my attempts:

print [a for innerList in fin_list1 for a,b in innerList]

Output:

['1', '12', '3', '21', '31', '11']

But, as you can see, although I successfully retrieved the second element of each tuple, I could not save my internal list structure.

+4
source share
3 answers

First, let's assign the data:

>>> data = [
  [('a', '1'), ('a', '12'), ('a', '3')],
  [('b', '21'), ('b', '31')],
  [('c', '11')],
]

You can use itemgetterto create a function that gets one element from a tuple:

>>> from operator import itemgetter
>>> first = itemgetter(0)
>>> second = itemgetter(1)

map:

>>> [map(first, row) for row in data]
[['a', 'a', 'a'], ['b', 'b'], ['c']]
>>> [map(second, row) for row in data]
[['1', '12', '3'], ['21', '31'], ['11']]

first second itemgetter:

def first(xs):
    return xs[0]

def second(xs):
    return xs[1]
+3

:

>>> l = [[('a', '1'), ('a', '12'), ('a', '3')], [('b', '21'), ('b', '31')], [ ('c', '11')]]

- :

>>> [y for sublist in l for x, y in sublist]
['1', '12', '3', '21', '31', '11']

, , ,

, . , , :

>>> [[y for x, y in sublist] for sublist in l]
[['1', '12', '3'], ['21', '31'], ['11']]

, , map, .

+4
the_list = [[('a', '1'), ('a', '12'), ('a', '3')], [('b', '21'), ('b', '31')], [ ('c', '11')]]

new_list = [[x[1] for x in y] for y in the_list]

print new_list

:

[['1', '12', '3'], ['21', '31'], ['11']]

+1

Source: https://habr.com/ru/post/1614180/


All Articles