# 在 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.