不要使用列表作为变量名
编辑,最初被误读为第二高的索引 - 现在已修复,thanx Jean-François Fabre
lst = [7,3,6,4,6]
lst.index(sorted(lst)[1])
Out[161]: 3
lst[3]
Out[162]: 4
sorted(lst)
Out[163]: [3, 4, 6, 6, 7]
上面有输入列表中重复数字的问题,通过使用.index可以得到第一个匹配的索引
lst = [1, 1, 7,3,6,4,6]
lst.index(sorted(lst)[1])
Out[9]: 0 # 0 is wrong, the postion of the 2nd smallest is 1
我认为这可以解决问题
n = 1
sorted([*enumerate(lst)], key=lambda x: x[1])[n][0]
Out[11]: 1
看碎片
[*enumerate(lst)]
Out[12]: [(0, 1), (1, 1), (2, 7), (3, 3), (4, 6), (5, 4), (6, 6)]
enumerate 将计数与输入 lst 中的值配对,* 强制“解包”枚举对象,外部方括号在 list 中“捕获”此输出
在 Python 内置 sorted 中,第二个参数 key=lambda x: x[1] 告诉它查找来自 [*enumerate(lst)] 的元组的第二个位置,它们是来自 lst 的数字
sorted([*enumerate(lst)], key=lambda x: x[1])
Out[13]: [(0, 1), (1, 1), (3, 3), (5, 4), (4, 6), (6, 6), (2, 7)]
使用[n][0] 对列表进行索引获取第n 个排序的元组,并从元组中获取第一个值,即enumerate 中指定的索引