python-3.x - 在 Python3 中查找整数和字符串列表中最小数字的索引
问题描述
我之前在 Python 2.7 中有代码,我可以在整数和字符串列表中找到最小数字的索引。我以前用下面的例子做过这个:
list = ["NA",2,3,1]
min_num_position = list.index(min(list))
return min_num_position
>>>3
我已经升级到 Python 3,上面的相同代码会引发类型错误,因为我正在混合字符串和整数:
TypeError: '<' not supported between instances of 'int' and 'str'
我的问题是是否有类似的简单方法可以在 Python 3 中保持相同的功能?如果可能,我想避免正则表达式或多个循环或编写自定义函数。
解决方案
你可以建立一个没有字符串的'子列表,然后调用min
它:
min_num = lst.index(min([x for x in lst if not isinstance(x, str)]))
当然,如果您需要字符串仍然存在时的“原始”索引,您可以用一个巨大的数字替换它们(如果您知道其他数字的上限),这样它们就永远不会是“最小”值:
min_num = lst.index(min([x if not isinstance(x, str) else 99999 for x in lst]))
推荐阅读
- vuejs2 - 如何动态设置类名?
- javascript - 创建带参数的 Promise
- java - 当从另一个类调用使用它的方法时,为什么自动装配对象为空?
- button - 角度日期选择器未显示在 mat-menu 中
- swift - 在 Swift 中使用 available
- python - 无法使用 pip install spacy 安装 spacy
- javascript - 如何复制 JavaScript 生成的文本?
- pandas - 分解时间间隔并将它们分配给相应的时间
- vue.js - 安装 Nuxt.js 失败
- python - 如何将flask_jwt_extended 与蓝图一起使用?