假設我有一個來自 torunament 的點串列
points = [0, 12, 9]
我想要一個球員的排名,所以預期的輸出是
[1, 2, 0]
因為排名第一的是索引1,然后是索引2,然后是索引0。我的想法是使用for遍歷所有數字,得到最大值,找到最大值的索引,然后賦值在排名上,卻顯得不必要冗長繁復。有小費嗎?
uj5u.com熱心網友回復:
使用sorted:
points = [0, 12, 9]
res = sorted(range(len(points)), key=lambda x: points[x], reverse=True)
print(res)
輸出
[1, 2, 0]
這個想法是range(3)根據串列中的值對串列 ( )的索引進行排序,因此key=lambda x: points[x]. 相反的 True 是因為您想要降序排名。
uj5u.com熱心網友回復:
points = [0, 12, 9]
points_and_indices = [(p, i) for i, p in enumerate(points)]
points_and_indices.sort(reverse=True)
indices = [i for p, i in points_and_indices]
print(indices)
輸出:
[1, 2, 0]
更新
你在評論中說
獲得該分數的第一個指數領先
Python 排序保證穩定,但排序與reverse=True穩定正向排序相反,這會導致上述解決方案對您的目的而言是錯誤的。
為了解決這個問題,可以根據負分進行排序,也可以將其壓縮為一行,如下所示:
points = [0, 12, 9, 12]
indices = [i for _, i in sorted((-p, i) for i, p in enumerate(points))]
print(indices)
輸出:
[1, 3, 2, 0]
uj5u.com熱心網友回復:
另一種解決方案可能是:
points = [0, 12, 9]
s = points[:]
s.sort()
for i in range(len(s)):
s[i] = points.index(s[i])
print(s)
它將 points 變數排序到一個名為的新串列中s,然后s通過索引更改其中的值points
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/342470.html
標籤:Python
