1

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]]
1
  • 1
    Firstly can you explain what the desired result is supposed to be, secondly can you show your efforts Commented Nov 24, 2016 at 13:34

4 Answers 4

4

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]]
Sign up to request clarification or add additional context in comments.

Comments

2

similar using nested list comprehension with a little variance from @Moses Koledoye answer

lst = [[(1,0.99), (2,0.95)], [(2,0.97),(3,0.89),(1, 0.80)]]
result = [[i[0] for i in j] for j in lst]
# result = [[1, 2], [2, 3, 1]]

Comments

1

You can do this with groupby from the itertools module:

import itertools

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

print [[x[0] for x in k] for k, g in itertools.groupby(L)]

Comments

0

Another option is to use a more functional approach. Use operator.itemgetter to construct a callable object that fetches the initial item from a collection, and apply it to each row of the main list using map.

from operator import itemgetter

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

ig0 = itemgetter(0)
print([list(map(ig0, row)) for row in lst])

output

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.