简体   繁体   中英

Get set with smallest 3rd value in python

I have an array. This iterator-object including multiple tuples of length 3. I would like to pick a tuple with the smallest third value.

for example (I just wrote it down as a list but it's not a list)

a = [(1, 5, 4), (2, 5, 0.4), (3, 4, 0.4), (1, 9, 0.3)]

the output should be:

(1, 9, 0.3)

Use min with a custom key fetching the 3rd value

values = [(1, 5, 4), (2, 5, 0.4), (3, 4, 0.4), (1, 9, 0.3)]

min_tuple = min(values, key=lambda x: x[2])
print(min_tuple)  # (1, 9, 0.3)

you can do an algorithm with linear complexity that will iterate in the in the array and find the smallest using the min function

and convert into tuple

Code:

def smallest(a):
    result = []
    for x in a:
        result.append(min(x))
    return result
a=[(1, 5, 4), (2, 5, 0.4), (3, 4, 0.4), (1, 9, 0.3)]
print(smallest(a)) #(1, 9, 0.3)
import functools a = [(1, 5, 4), (2, 5, 0.4), (3, 4, 0.4), (1, 9, 0.3)] print(functools.reduce(lambda c, m: m if m[2] < c[2] else c, a))

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