2

Say I have a list of tuples, like the following:

listo = [('a','1'),('b','0'),('c','2'),('d','0')] 

If I want the lowest tuple, based on the second index of each tuple, I can customize the min function with a lambda function, like this:

min(listo, key=lambda x: x[1]) 

As it stands, this code would return:

In [31]: min(listo, key=lambda x: x[1]) Out[31]: ('b', '0') 

But this only gives me one tuple, and only the first one it encounters at that. What if I wanted ALL the min tuples? So it returns something like:

In [31]: min(listo, key=lambda x: x[1]) Out[31]: [('b', '0'),('d','0')] 

Any advice on how to accomplish this?

1 Answer 1

5

You can do it by first searching one minimum value and then look for another ones based by the minimum value found.

listo = [('a','1'),('b','0'),('c','2'),('d','0')] minValue = min(listo, key=lambda x: x[1])[1] minValueList = [x for x in listo if x[1] == minValue] 

Another approach could be making your own minimum function that uses some kind of list of minimum values but probably it would be much slower for bigger problems.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, I was kind of doing the second approach already, but was looking for a more "Pythonic" way. I like this, thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.