简体   繁体   English

使用 Python Lambda function 从元组中过滤最大值

[英]Filter the maximum from a tuple using Python Lambda function

I have a list of tuples like below:我有一个如下的元组列表:

data = [(0.5, 0, 0), (0.4, 0, 0), (0.6, 0, 0)]

I want to find the maximum value over the first element of each tuple using a lambda function.我想使用lambda function 在每个元组的第一个元素上找到最大值。 In this case, the expected result would be 0.6.在这种情况下,预期结果将是 0.6。

I'd usually write this like this:我通常会这样写:

>>> a = [(0.5, 0, 0), (0.4, 0, 0),(0.6, 0, 0)]
>>> max(x for x, y, z in a)
0.6

Since you have the strange requirement to use a lambda function, you can also do由于您有使用 lambda function 的奇怪要求,您也可以这样做

>>> max(a, key=lambda x: x[0])[0]
0.6

However, this is more complicated than necessary, and other than your random requirement there is no reason to do this.但是,这比必要的复杂,除了您的随机要求之外,没有理由这样做。

l = [(0.5, 0, 0), (0.4, 0, 0),(0.6, 0, 0)]

y = max(map(lambda x: x[0], l))
print(y)

>>> 0.6

Usually people want the item (tuple) that contains the maximum first value, rather than just the max first value.通常人们想要包含最大第一个值的项目(元组),而不仅仅是最大第一个值。 This is exactly when having a lambda is useful:这正是使用lambda有用的时候:

>>> data = [(0.5, 0, 0), (0.4, 0, 0), (0.6, 0, 0)]
>>> max(data, key=lambda x: x[0])
(0.6, 0, 0)

Or the most simple - if you want only the max first value and not the tuple with the max value - is without a lambda:或者最简单的 - 如果你只想要最大的第一个值而不是具有最大值的元组 - 没有 lambda:

>>> max(x[0] for x in data)
0.6

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

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