在元组列表中查找元组(按多个键排序) [英] Finding tuple in the list of tuples (sorting by multiple keys)
本文介绍了在元组列表中查找元组(按多个键排序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在元组列表中找到元组,但没有获取操作方法
I am trying to find tuple in the list of tuple, but not getting how to do that
我有以下list (id, price, count)
[('1', 3.0, 6), ('2', 2.0, 2), ('3', 2.0, 5), ('4', 4.0, 2), ('5', 2.0, 5), ('
6', 3.0, 6), ('7', 3.0, 5), ('8', 2.0, 5), ('9', 3.0, 5), ('10', 3.0, 5)]
查找元组的条件是:
- 元组应具有最小的
price
. - 元组的最大计数应为
value
. - 第一个条件的优先级高于第二个条件.
- tuple should have minimum
price
. - tuple should have maximum count
value
. - priority of first condition is higher then second condition.
请告诉我如何实现这些条件才能在列表中找到元组.
Please tell me how to achieve these conditions to find tuple in the list.
推荐答案
您可以为从列表项的两个元素中排序:(price, -count)
(减用来反转方向的计数-较大的值将首先出现):
You can build key for sorted from two elements of your list items: (price, -count)
(minus count used to invert direction - bigger value will be first in result):
t = [('1', 3.0, 6), ('2', 2.0, 2), ('3', 2.0, 5), ('4', 4.0, 2), ('5', 2.0, 5),
('6', 3.0, 6), ('7', 3.0, 5), ('8', 2.0, 5), ('9', 3.0, 5), ('10', 3.0, 5)]
>>> sorted(t, key=lambda i: (i[1], -i[2]))
[('3', 2.0, 5), ('5', 2.0, 5), ('8', 2.0, 5), ('2', 2.0, 2), ('1', 3.0, 6),
('6', 3.0, 6), ('7', 3.0, 5), ('9', 3.0, 5), ('10', 3.0, 5), ('4', 4.0, 2)]
要仅查找一个元素,可以使用具有相同功能的 min 函数元组作为关键参数:
To find only one element you can use min function with same tuple as key argument:
>>> min(t, key=lambda i: (i[1], -i[2]))
('3', 2.0, 5)
这篇关于在元组列表中查找元组(按多个键排序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文