简体   繁体   中英

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. In this case, the expected result would be 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

>>> 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:

>>> 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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