在 Python 中找出列表中元素的相對順序


我們有一個由整數構成的列表。我們需要找出相對順序,即如果按升序對它們進行排序,則我們需要找出它們所在位置的索引。

已排序的和索引

我們首先對整個列表進行排序,然後找出它們在排序後的每個索引。

示例

 即時演示

listA = [78, 14, 0, 11]
# printing original list
print("Given list is : \n",listA)
# using sorted() and index()
res = [sorted(listA).index(i) for i in listA]
# printing result
print("list with relative ordering of elements : \n",res)

輸出

執行以上程式碼,得到以下結果 -

Given list is :
[78, 14, 0, 11]
list with relative ordering of elements :
[3, 2, 0, 1]

已列舉和已排序的

使用列舉和排序函式,我們檢索每個元素,然後建立一個包含列舉和已排序函式的字典容器。我們透過對映函式獲取透過此容器的每個元素。

示例

 即時演示

listA = [78, 14, 0, 11]
# printing original list
print("Given list is : \n",listA)
# using sorted() and enumerate
temp = {val: key for key, val in enumerate(sorted(listA))}
res = list(map(temp.get, listA))
# printing result
print("list with relative ordering of elements : \n",res)

輸出

執行以上程式碼,得到以下結果 -

Given list is :
[78, 14, 0, 11]
list with relative ordering of elements :
[3, 2, 0, 1]

更新日期: 04-6 月-2020

387 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告