Python 按子列表中的第二个元素对列表进行排序

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]]

使用sort()方法根据子列表中的第二个元素对列表进行排序的Python程序。

示例

# 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]]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程