# 在 Python 中对元组进行排序

Vaibhhav Khetarpal 2023年1月30日

## 在 Python 中使用 list.sort() 函数对 Tuple 列表进行排序

list.sort() 函数按升序或降序对一个列表的元素进行排序。它的 key 参数指定在排序中要使用的值。key 应是一个函数或其他可调用的函数，可以应用于每个列表元素。

list_students = [
("Vaibhhav", 86),
("Manav", 91),
("Rajesh", 88),
("Sam", 84),
("Richie", 89),
]

# sort by second element of tuple
list_students.sort(key=lambda x: x[1])  # index 1 means second element

print(list_students)

[('Sam',84), ('Vaibhhav',86), ('Rajesh',88), ('Richie',89), ('Manav',91)]

list_students = [
("Vaibhhav", 86),
("Manav", 91),
("Rajesh", 88),
("Sam", 84),
("Richie", 89),
]

# sort by second element of tuple
list_students.sort(key=lambda x: x[1], reverse=True)

print(list_students)

[('Manav',91), ('Richie',89), ('Rajesh',88), ('Vaibhhav',86), ('Sam',84)]

## 使用 Python 中的冒泡排序算法对 Tuple 列表进行排序

list_ = [("Vaibhhav", 86), ("Manav", 91), ("Rajesh", 88), ("Sam", 84), ("Richie", 89)]

# sort by second element of tuple
pos = 1
list_length = len(list_)

for i in range(0, list_length):
for j in range(0, list_length - i - 1):
if list_[j][pos] > list_[j + 1][pos]:
temp = list_[j]
list_[j] = list_[j + 1]
list_[j + 1] = temp

print(list_)

[('Sam',84), ('Vaibhhav',86), ('Rajesh',88), ('Richie',89), ('Manav',91)]

pos 变量指定了进行排序的位置，在本例中，就是第二个元素。

list_ = [("Vaibhhav", 86), ("Manav", 91), ("Rajesh", 88), ("Sam", 84), ("Richie", 89)]

# sort by first element of tuple
pos = 0
list_length = len(list_)
for i in range(0, list_length):
for j in range(0, list_length - i - 1):
if list_[j][pos] > list_[j + 1][pos]:
temp = list_[j]
list_[j] = list_[j + 1]
list_[j + 1] = temp

print(list_)

[('Manav',91), ('Rajesh',88), ('Richie',89), ('Sam',84), ('Vaibhhav',86)]

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.