Python程序根据子列表中的第二个元素对列表进行排序。
给定列表,我们的任务是根据子列表中的第二个元素对列表进行排序。在这里,我们应用简单的冒泡排序。
示例
Input : [['CCC', 15], ['AAA', 10], ['RRRR', 2],['XXXX', 150]] Output : [['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]
算法
Step 1: Given a list. Step 2: We have tried to access the second element of the sublists using the nested loops. Step 3: Traverse through all array elements. Step 4: Last i elements are already in place. Step 5: traverse the array from 0 to n-i-1. Step 6: Swap if the element found is greater than the next element.
范例程式码
# Python program to sort the lists using the second element of sublist
# In place way to sort, use of third variable.
def sortlist(A):
l = len(A)
for i in range(0, l):
for j in range(0, l-i-1):
if (A[j][1] > A[j + 1][1]):
tempo = A[j]
A[j]= A[j + 1]
A[j + 1]= tempo
return A
# Driver Code
A = [['AAA', 10], ['CCC', 15], ['RRRR', 2], ['XXXX', 150]]
print(sortlist(A))输出结果
[['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短