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]]
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]]
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]]
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)]
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]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.