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