ssh26 ssh26 - 11 days ago 6
Python Question

How to get list from list of list of tuples in python

I have a list of list of tuples:

[[(1,0.99), (2,0.95)], [(2,0.97),(3,0.89),(1, 0.80)]]


From the above data how can I get the list of list such as:

[[1,2],[2,3,1]]

Answer

You can simply use a nested list comprehension:

lst = [[(1,0.99), (2,0.95)], [(2,0.97),(3,0.89),(1, 0.80)]]

r = [[i for i, _ in l] for l in lst]
print(r)
# [[1, 2], [2, 3, 1]]

Reference:

List comprehensions

Comments