我有一个数字列表:
myList = [1, 2, 3, 100, 5]
Run Code Online (Sandbox Code Playgroud)
现在,如果我对此列表进行排序以获取[1, 2, 3, 5, 100].我想要的是排序顺序中原始列表中元素的索引,即[0, 1, 2, 4, 3]
--- ala MATLAB的sort函数,它返回值和索引.
如果我想要列表中的最大值,我可以写max(List),但如果我还需要最大值的索引怎么办?
我可以这样写:
maximum=0
for i,value in enumerate(List):
if value>maximum:
maximum=value
index=i
Run Code Online (Sandbox Code Playgroud)
但这对我来说看起来很乏味.
如果我写:
List.index(max(List))
Run Code Online (Sandbox Code Playgroud)
然后它将迭代列表两次.
有没有更好的办法?