简体   繁体   English

如何从python中的元组列表列表中获取列表

[英]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]]

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 与嵌套列表推导类似,与@Moses Koledoye答案略有不同

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: 您可以通过itertools模块中的groupby来执行此操作:

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 . 使用operator.itemgetter构造一个可调用对象,该对象从集合中获取初始项,然后使用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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM