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)
CodePudding user response:
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)
CodePudding user response:
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))
CodePudding user response:
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)