Python 程序根据子列表中的第二个元素对列表进行排序。
programmingpythonserver side programming
在本文中,我们将根据子列表中的第二个元素对列表进行排序。假设我们有以下列表 -
[['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]]