pagib
pagib

Reputation: 3

get multiple tuples from list of tuples using min function

I have a list that looks like this

mylist = [('Part1', 5, 5), ('Part2', 7, 7), ('Part3', 11, 9), ('Part4', 45, 45), ('part5', 5, 5)]

I am looking for all the tuples that has a number closest to my input

now i am using this code

result = min([x for x in mylist if x[1] >= 4 and x[2] >= 4])

The result i am getting is

('part5', 5, 5)

But i am looking for an result looking more like

[('Part1', 5, 5), ('part5', 5, 5)]

and if there are more tuples in it ( i have 2 in this example but it could be more) then i would like to get all the tuples back

the whole code

mylist = [('Part1', 5, 5), ('Part2', 7, 7), ('Part3', 11, 9), ('Part4', 45, 45), ('part5', 5, 5)]
result = min([x for x in mylist if x[1] >= 4 and x[2] >= 4])
print(result)

Upvotes: 0

Views: 29

Answers (1)

SpghttCd
SpghttCd

Reputation: 10880

threshold = 4
mylist = [('Part1', 5, 5), ('Part2', 7, 7), ('Part3', 11, 9), ('Part4', 45, 45), ('part5', 5, 5)]

filtered = [x for x in mylist if x[1] >= threshold and x[2] >= threshold]
keyfunc = lambda x: x[1]
my_min = keyfunc(min(filtered, key=keyfunc))

result = [v for v in filtered if keyfunc(v)==my_min]


# [('Part1', 5, 5), ('part5', 5, 5)]

Upvotes: 1

Related Questions