[英]How to get the max value from list of tuples of tuples (?)
My data looks something like this:我的数据看起来像这样:
I have a list d where我有一个列表 d 在哪里
d = [(0, [(1, 0.15122674), (2, 0.59446937), (3, 0.06613562), (4, 0.1877523)]),
(1, [(1, 0.46739018), (4, 0.5283537)]),
(2, [(1, 0.99668014)])]
I would like to have an output of:我想要输出:
[(0, [(2, 0.59446937)]),
(1, [(4, 0.5283537)]),
(2, [(1, 0.99668014)])]
Where we are taking the max value, looking at the 2nd value of these tuples.我们取最大值的地方,查看这些元组的第二个值。
I'm not too sure where to start because I am python beginner.我不太确定从哪里开始,因为我是 python 初学者。 I understand if this was a simple list of tuples we could do something like:
我明白如果这是一个简单的元组列表,我们可以这样做:
max(d,key=lambda x:x[1])
but given the structure of my data, I'm not too sure how to go about this one...但考虑到我的数据结构,我不太确定如何处理这个......
You can use a list comprehension and operator.itemgetter
to make it much easier:您可以使用列表理解和
operator.itemgetter
使其更容易:
In [9]: from operator import itemgetter
In [10]: [(i, max(j, key=itemgetter(1))) for i, j in d]
Out[10]: [(0, (2, 0.59446937)), (1, (4, 0.5283537)), (2, (1, 0.99668014))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.