Python:在浮点列表中查找最小项的索引 [英] Python: Find index of minimum item in list of floats

查看:496
本文介绍了Python:在浮点列表中查找最小项的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python列表中找到最小项目的索引?如果他们是整数,我会简单地做:

$ $ $ p $ minIndex = myList.index(min(myList))

但是,浮动列表出现以下错误,我认为是因为浮动等值比较比较麻烦。

  ValueError:0.13417985135不在列表中

现在,我知道我可以简单地滚动列表并比较每个项目,看它是否是< (min + 0.0000000000001)和>(min - 0.0000000000001),但这有点凌乱。有一个更优雅的(最好是内置的)的方式来找到浮动列表中最小的项目的索引?

解决方案

你有效地扫描列表一次找到最小值,然后再次扫描找到索引,你可以一次完成:

 来自操作员导入itemgetter 
min(枚举(a),key = itemgetter(1))[0]


How can I find the index of the minimum item in a Python list of floats? If they were integers, I would simply do:

minIndex = myList.index(min(myList))

However, with a list of floats I get the following error, I assume because float equality comparison is rather iffy.

ValueError: 0.13417985135 is not in list

Now, I know that I could simply scroll through the list and compare each item to see whether it is < (min + 0.0000000000001) and > (min - 0.0000000000001), but that is kinda messy. Is there a more elegant (preferably built-in) way to find the index of the smallest item in a list of floats?

解决方案

You're effectively scanning the list once to find the min value, then scanning it again to find the index, you can do both in one go:

from operator import itemgetter
min(enumerate(a), key=itemgetter(1))[0] 

这篇关于Python:在浮点列表中查找最小项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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