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]]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP