在 Python 中对列表列表进行排序

Samyak Jain 2023年10月10日

在 Python 中使用运算符模块中的 `itemgetter()` 函数和 `sorted()` 函数对列表列表进行排序

``````from operator import itemgetter

A = [[10, 8], [90, 2], [45, 6]]
print("Sorted List A based on index 0: % s" % (sorted(A, key=itemgetter(0))))
B = [[50, "Yes"], [20, "No"], [100, "Maybe"]]
print("Sorted List B based on index 1: % s" % (sorted(B, key=itemgetter(1))))
``````

``````Sorted List A based on index 0: [[10, 8], [45, 6], [90, 2]]
Sorted List B based on index 1: [[100, 'Maybe'], [20, 'No'], [50, 'Yes']]
``````

``````from operator import itemgetter

C = [[10, 8, "Cat"], [90, 2, "Dog"], [45, 6, "Bird"]]
print(
"Reversed sorted List C based on index 1: % s"
% (sorted(C, key=itemgetter(1), reverse=True))
)
``````

``````Reverse sorted List C based on index 1: [[10, 8, 'Cat'], [45, 6, 'Bird'], [90, 2, 'Dog']]
``````

在 Python 中使用 `lambda` 表达式和 `sorted()` 函数对列表列表进行排序

`lambda` 表达式是 Python 中的简单单行函数。

``````A = [[100, "Yes"], [40, "Maybe"], [60, "No"]]
print("Sorted List A based on index 0: % s" % (sorted(A, key=lambda x: x[0])))
B = [[2, "Dog"], [0, "Bird"], [7, "Cat"]]
print("Sorted List A based on index 1: % s" % (sorted(B, key=lambda x: x[1])))
``````

``````Sorted List A based on index 0: [[40, 'Maybe'], [60, 'No'], [100, 'Yes']]
Sorted List B based on index 1: [[0, 'Bird'], [7, 'Cat'], [2, 'Dog']]
``````

``````C = [[60, 5], [90, 7], [30, 10]]
print(
"Reversed sorted List C based on index 0: % s"
% (sorted(C, key=lambda x: x[0], reverse=True))
)
``````

``````Reversed sorted List C based on index 0: [[90, 7], [60, 5], [30, 10]]
``````

在 Python 中使用 `sort()` 函数对列表列表进行排序

`sort()` 方法根据每个内部列表的第一个元素对 Python 中的列表列表进行排序。此方法对原始列表本身进行更改。我们使用 `reverse` 参数按降序排序。

``````A = [[55, 90], [45, 89], [90, 70]]
A.sort()
print("New sorted list A is % s" % (A))
A.sort(reverse=True)
print("New reverse sorted list A is % s" % (A))
``````

``````New sorted list A is [[45, 89], [55, 90], [90, 70]]
New reverse sorted list A is [[90, 70], [55, 90], [45, 89]]
``````

``````A = [[5, 90, "Hi", 66], [80, 99], [56, 32, 80]]
A.sort(key=len)
print("New sorted list A is % s" % (A))
``````

``````New sorted list A is [[80, 99], [56, 32, 80], [5, 90, 'Hi', 66]]
``````