Python程式中按任意鍵對元組進行升序排序


在本教程中,我們將學習如何按第n個索引鍵對元組列表進行升序排序。例如,我們有一個元組列表**[(2, 2), (1, 2), (3, 1)]**,我們需要使用第0個索引元素對其進行排序。該列表的輸出將是**[(1, 2), (2, 2), (3, 1)]**。

我們可以使用**sorted**方法實現這一點。在將列表傳遞給**sorted**函式時,我們必須傳遞一個**key**。這裡,key是排序所基於的索引。

**sorted**接受一個列表,並返回按升序排列的列表。如果要按降序排列列表,則在**sorted**函式中將**reverse**關鍵字引數設定為**True**。

讓我們看看解決問題的步驟。

演算法

1. Initialize list of tuples and key
2. Define a function. 2.1. Return key-th index number.
3. Pass list of tuples and function to the sorted function. We have to pass function name to
the keyword argument key. Every time one element (here tuple) to the function. The
function returns key-th index number.
4. Print the result.

示例

## list of tuples
tuples = [(2, 2), (1, 2), (3, 1)]
## key
key = 0
## function which returns the key-th index number from the tuple
def k_th_index(one_tuple):
return one_tuple[key]
## calling the sorted function
## pass the list of tuples as first argument
## give the function as a keyword argument to the **key**
sorted(tuples, key = k_th_index)

輸出

如果執行上面的程式,您將得到以下結果。

[(1, 2), (2, 2), (3, 1)]

如果將key初始化為大於len(tuple) - 1的索引,則會得到索引錯誤。讓我們來看看。

示例

 線上演示

## list of tuples
tuples = [(2, 2), (1, 2), (3, 1)]
## key
## initializing the key which is greter than len(tuple) - 1
key = 2
## function which returns the key-th index number from the tuple
def k_th_index(one_tuple):
return one_tuple[key]
## calling the sorted function
## pass the list of tuples as first argument
## give the function as a keyword argument to the **key**
sorted(tuples, key = k_th_index)

輸出

如果執行上面的程式,您將得到以下結果。

IndexError Traceback (most recent call last)
<ipython-input-13-4c3fa14880dd> in <module>
13 ## pass the list of tuples as first argument
14 ## give the function as a keyword argument to the **key**
---> 15 sorted(tuples, key = k_th_index)
<ipython-input-13-4c3fa14880dd> in k_th_index(one_tuple)
8 ## function which returns the key-th index number from the tuple
9 def k_th_index(one_tuple):
---> 10 return one_tuple[key]
11
12 ## calling the sorted function
IndexError: tuple index out of range

上面的程式適用於任意數量的元組和任意大小的元組,除非索引不超過**len(tuple) - 1**。

結論

希望您喜歡本教程。如果您對本教程有任何疑問,請在評論區提出。

更新於:2019年10月23日

142 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告