包含两个条件的列表中的最大值 [英] Max in a list with two conditions
本文介绍了包含两个条件的列表中的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Python中有一个列表,其中每个元素都是这样的元组:
I have a list in Python in which each element is a tuple like this:
(attr1, attr2, attr3)
我想找到具有最大attr2
但具有attr3 >= 100
的元组.
I want to find the tuple that has the largest attr2
, but that have attr3 >= 100
.
什么是pythonic方法?
What is the pythonic approach to this?
推荐答案
必须同时过滤并使用key
自变量作为max:
You have to both filter and use a key
argument to max:
from operator import itemgetter
max(filter(lambda a: a[2] >= 100, yourlist), key=itemgetter(1))
过滤器也可以表示为生成器表达式:
The filter can also be expressed as a generator expression:
max((t for t in yourlist if t[2] >= 100), key=itemgetter(1))
演示:
>>> yourlist = [(1, 2, 300), (2, 3, 400), (3, 6, 50)]
>>> max((t for t in yourlist if t[2] >= 100), key=itemgetter(1))
(2, 3, 400)
>>> max(filter(lambda a: a[2] >= 100, yourlist), key=itemgetter(1))
(2, 3, 400)
请注意,由于您进行了过滤,因此很容易以一个空列表来选择最大值,因此除非您需要该异常沿调用堆栈向上传播,否则您可能需要捕获ValueError
s:
Note that because you filter, it's easy to end up with an empty list to pick the max from, so you may need to catch ValueError
s unless you need that exception to propagate up the call stack:
try:
return max(filter(lambda a: a[2] >= 100, yourlist), key=itemgetter(1))
except ValueError:
# Return a default
return (0, 0, 0)
这篇关于包含两个条件的列表中的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文