# 在 Python 中對二維陣列進行排序

`sort()` 方法就地修改列表，`sorted()` 內建函式從可迭代物件構建一個新的排序列表。我們還將研究為 `sort()``sorted()` 函式定義可迭代的不同方法。

## 使用 Python 中的 `sort()` 函式按列號對二維陣列進行排序

``````lst = [["John", 5], ["Jim", 9], ["Jason", 0]]

lst.sort(key=lambda x: x[1])
print(lst)
``````

``````[['Jason', 0], ['John', 5], ['Jim', 9]]
``````

``````lst = [
("john", "C", 15),
("jane", "A", 12),
("dave", "D", 10),
]

lst.sort(key=lambda lst: lst[2])
print(lst)
``````

``````[('dave', 'D', 10), ('jane', 'A', 12), ('john', 'C', 15)]
``````

## 使用 Python 中的 `sorted()` 函式按列號對二維陣列進行排序

``````li = [["John", 5], ["Jim", 9], ["Jason", 0]]

sorted_li = sorted(li, key=lambda x: x[1])
print(sorted_li)
``````

``````[['Jason', 0], ['John', 5], ['Jim', 9]]
``````

`key` 也可以使用庫 `operator` 中的 `itemgetter` 來定義。

``````from operator import itemgetter

lst = [
("john", "C", 15),
("jane", "A", 12),
("dave", "D", 10),
]

sorted_lst = sorted(lst, key=itemgetter(1))
print(sorted_lst)
``````

``````[('jane', 'A', 12), ('john', 'C', 15), ('dave', 'D', 10)]
``````

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.