Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top