首页 > 解决方案 > 在 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 中保持相同的功能?如果可能,我想避免正则表达式或多个循环或编写自定义函数。

标签: python-3.x

解决方案


你可以建立一个没有字符串的'子列表,然后调用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]))

推荐阅读