我可以使用Python的Min函数返回所有min元组的列表吗? [英] Can I return a list of ALL min tuples, using Python's Min function?

查看:79
本文介绍了我可以使用Python的Min函数返回所有min元组的列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个元组列表,如下所示:

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

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

如果我想要最低的元组,则基于每个元组的第二个索引,我可以使用lambda函数自定义min函数,如下所示:

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')

但这只给了我一个元组,也只有一个元组.如果我想要所有min元组怎么办?因此它返回类似:

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?

推荐答案

您可以先搜索一个最小值,然后根据找到的最小值查找另一个最小值.

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.

这篇关于我可以使用Python的Min函数返回所有min元组的列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆