-1

I have a list in the following form:

l0=[[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]

How one turns this into:

l=[2,3,5,7,1]

I tried:

l=[x[1] for x in l0]

which gives:

#[('x1', 3), ('x3', 7)]

Edit: In order not to lose track of elements is there also anyway to have the output as:

l=[[2,3],[5,7,1]]

So one does not use flattening.

Will
  • 47
  • 5

5 Answers5

2

You can add an extra loop to your comprehension:

l0=[[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]

l=[x[1] for i in l0 for x in i]
print(l)
# [2, 3, 5, 7, 1]
DavidG
  • 24,279
  • 14
  • 89
  • 82
1

For your new question, you can use a nested comprehension.

lst0 = [[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]
lst = [[t[1] for t in u] for u in lst0]
print(lst)

output

[[2, 3], [5, 7, 1]]

I changed the names of the lists since l0 and l aren't very readable in most fonts: the l is too similar to 1.


As an alternative, you could do this using map although Guido isn't fond of this construction:

from operator import itemgetter

lst0 = [[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]
print([list(map(itemgetter(1), u)) for u in lst0])

In Python 2, you can omit the list wrapper:

print [map(itemgetter(1), u) for u in lst0]
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

You could iterate over the list and append it to a new one.

l0=[[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]

out = []
for a in l0:
    out.append([x[0] for x in a])
print(out)
bbrg
  • 119
  • 1
  • 7
-1

you first have to flatten the list like this flat_list = [item for sublist in l0 for item in sublist] and then do your thing l=[x[1] for x in flat_list]

Ostoja
  • 119
  • 8
-2

try to use the index, your l0 is a list: https://www.tutorialspoint.com/python/python_lists.htm

l0=[[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]
l=(l0[0][0][1],l0[0][1][1],l0[1][0][1],l0[1][1][1],l0[1][2][1])
print(l)

(2, 3, 5, 7, 1)

Tom92
  • 5
  • 1
  • 3
  • Ok, that works, as long as the sizes of the lists don't change. But it's too verbose, and too easy to make a mistake with all of those indices. – PM 2Ring Apr 25 '18 at 15:54
  • Yes of course he has to find a general formula (loop) to find this result – Tom92 Apr 26 '18 at 08:04