Python 程式用於根據子列表中的第二個元素對列表進行排序。


在本文中,我們將根據子列表中的第二個元素對列表進行排序。假設我們有以下列表 −

[['jack', 50], ['antony', 20], ['jones', 87], ['gary', 70], ['tom', 90], ['sam', 110], ['warner', 65]]

輸出應如下所示,即根據第二個元素排序 −

[['antony', 20], ['jack', 50], ['warner', 65], ['gary', 70], ['jones', 87], ['tom', 90], ['sam', 110]]

Python 程式用於根據子列表中的第二個元素對列表進行排序,此方法採用 sort() 方法

示例

# Custom Function def SortFunc(sub_li): sub_li.sort(key = lambda x: x[1]) return sub_li # Driver Code subList =[['jack', 50], ['antony', 20], ['jones', 87], ['gary', 70], ['tom', 90], ['sam', 110], ['warner', 65]] print("Unsorted List = \n",subList) print("\nSorted List according to the second elemnt in the sublist =\n ",SortFunc(subList))

輸出

Unsorted List = 
[['jack', 50], ['antony', 20], ['jones', 87], ['gary', 70], ['tom', 90], ['sam', 110], ['warner', 65]]

Sorted List according to the second elemnt in the sublist =
  [['antony', 20], ['jack', 50], ['warner', 65], ['gary', 70], ['jones', 87], ['tom', 90], ['sam', 110]]

Python 程式用於根據子列表中的第二個元素對列表進行排序,此方法採用氣泡排序

示例

# Custom Function def SortFunc(subList): l = len(subList) for i in range(0, l): for j in range(0, l-i-1): if (subList[j][1] > subList[j + 1][1]): temp = subList[j] subList[j]= subList[j + 1] subList[j + 1]= temp return subList # Driver Code subList =[['jack', 50], ['antony', 20], ['jones', 87], ['gary', 70], ['tom', 90], ['sam', 110], ['warner', 65]] print("Unsorted List = \n",subList) print("\nSorted List according to the second elemnt in the sublist =\n ",SortFunc(subList))

輸出

Unsorted List = 
 [['jack', 50], ['antony', 20], ['jones', 87], ['gary', 70], ['tom', 90], ['sam', 110], ['warner', 65]]

Sorted List according to the second elemnt in the sublist =
 [['antony', 20], ['jack', 50], ['warner', 65], ['gary', 70], ['jones', 87], ['tom', 90], ['sam', 110]]

Python 程式用於根據子列表中的第二個元素對列表進行排序,此方法採用 sorted() 方法

示例

# Custom Function def SortFunc(subList): return(sorted(subList, key = lambda a: a[1])) # Driver Code subList =[['jack', 50], ['antony', 20], ['jones', 87], ['gary', 70], ['tom', 90], ['sam', 110], ['warner', 65]] print("Unsorted List = \n",subList) print("\nSorted List according to the second elemnt in the sublist =\n ",SortFunc(subList))

輸出

Unsorted List = 
 [['jack', 50], ['antony', 20], ['jones', 87], ['gary', 70], ['tom', 90], ['sam', 110], ['warner', 65]]
Sorted List according to the second elemnt in the sublist =
  [['antony', 20], ['jack', 50], ['warner', 65], ['gary', 70], ['jones', 87], ['tom', 90], ['sam', 110]]

更新於: 11-Aug-2022

1K+ 檢視次數

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.