Can I return a list of ALL min tuples, using Python's Min function?

爷,独闯天下 提交于 2020-12-16 05:49:42

问题


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:


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.



来源:https://stackoverflow.com/questions/17352387/can-i-return-a-list-of-all-min-tuples-using-pythons-min-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!