Hướng dẫn how do you sort a list in python custom? - làm thế nào để bạn sắp xếp một danh sách trong tùy chỉnh python?

Trong khoa học máy tính, một thuật toán sắp xếp đặt các yếu tố của một danh sách vào một thứ tự cụ thể. Chúng rất quan trọng vì chúng thường làm giảm sự phức tạp của một vấn đề. Hãy cùng khám phá cách sử dụng các chức năng sắp xếp tùy chỉnh để thực hiện các đơn đặt hàng và so sánh tùy chỉnh trong Python.

Trong bài viết trước của tôi về làm việc với các luồng trong Python, tôi đã giới thiệu ngắn gọn các phương thức sắp xếp với danh sách.sort () và Sắp xếp (). Cả list.sort()

>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
0 đều có tham số chính chỉ định hàm được gọi trên mỗi phần tử danh sách trước khi so sánh.

Trong bài viết này, tôi muốn đi xa hơn về chủ đề sắp xếp và khám phá cách viết một chức năng sắp xếp tùy chỉnh trong Python. Nói cách khác, tôi sẽ giải thích cách sử dụng hàm Lambda tùy chỉnh làm tham số chính.

Nếu bạn không thoải mái với các chức năng Python, bạn nên đọc cách xác định một chức năng trong Python trước khi đi sâu hơn vào bài viết này.

Sắp xếp với chức năng sắp xếp tùy chỉnh trong Python

Đầu tiên, hãy để nói về sự khác biệt giữa

>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
1 và
>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
0. Về mặt cú pháp,
>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
1 là một phương thức thể hiện được triển khai là
>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
4, trong khi
>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
0 được sử dụng là
>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
6.

Một điều quan trọng cần lưu ý là

>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
1 sửa đổi trực tiếp biến ban đầu và do đó, thứ tự ban đầu sẽ bị mất.

Mặt khác,

>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
0 giữ một bản sao của biến ban đầu, giúp bạn có thể trở lại thứ tự ban đầu nếu cần. Bởi vì
>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
1 không tạo ra bất kỳ bản sao nào của biến ban đầu, nên nó hiệu quả hơn một chút so với
>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
0. Tuy nhiên, điều này đến với chi phí thuận tiện.

Cũng cần lưu ý rằng

>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
0 sẽ trả về một danh sách; Do đó, bạn phải gán đầu ra cho một biến mới.

Đối với list.sort(), nó sửa đổi danh sách tại chỗ và không có giá trị trả về. Cuối cùng nhưng không kém phần quan trọng, list.sort() chỉ có thể hoạt động trong danh sách trong khi

>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
0 chấp nhận bất kỳ điều gì có thể.

Ví dụ: ở đây, một so sánh chuỗi không nhạy cảm trường hợp:

>>> sorted("LearnPython.com is awesome to learn about custom sort functions in Python".split(), key=str.lower)
['about', 'awesome', 'custom', 'functions', 'in', 'is'
 'Learn', 'LearnPython.com', 'Python', 'sort', 'to']

Lưu ý: Thông thường việc chuyển chức năng Lambda tùy chỉnh như một tham số chính để sắp xếp các đối tượng phức tạp trong Python. It is common to pass a custom lambda function as a key parameter to sort complex objects in Python.

Bây giờ, hãy để nói về các chức năng sắp xếp tùy chỉnh trong Python. Trong Python, chúng ta có thể viết các chức năng sắp xếp tùy chỉnh hoạt động với

>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
1 và
>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
0.

Giá trị của tham số chính phải là một hàm có một đối số duy nhất và trả về

>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7 cho mục đích sắp xếp. Bởi vì hàm chính chỉ được gọi một lần cho mỗi bản ghi đầu vào, đây là một cách hiệu quả để thực hiện phân loại trong Python.

Một mẫu phổ biến là sắp xếp các đối tượng phức tạp bằng cách sử dụng một số chỉ số đối tượng là

>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7. Ví dụ: chúng ta có thể xác định một đơn đặt hàng tùy chỉnh để sắp xếp danh sách các bộ dữ liệu:

>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

Nó cũng hoạt động cho các đối tượng có thuộc tính tên:

>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

Bạn có thể tìm hiểu thêm về các đối tượng tùy chỉnh trong Python trong bài viết Các bước đơn giản để tạo lớp của riêng bạn trong Python.

Biết cách thao tác dữ liệu, viết các chức năng sắp xếp tùy chỉnh trong Python và thực hiện các so sánh tùy chỉnh là những kỹ năng cần thiết để làm chủ. Giới thiệu của chúng tôi về Python cho khoa học dữ liệu là một cách tuyệt vời để chọn bộ kỹ năng theo yêu cầu này.

So sánh tùy chỉnh với chức năng sắp xếp trong Python

Bạn cũng có thể sử dụng

>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
0 với bộ so sánh tùy chỉnh làm tham số của nó.

Trong Python 2,

>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
0 có thể được triển khai với bộ so sánh tùy chỉnh,
>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 hoặc tham số
>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7.

Điều quan trọng cần lưu ý là

>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 cần vượt qua hai tham số (x và y) là các phần của danh sách. Nó sẽ trả về một số với logic sau:

  • Nếu nó trả về một số dương: x> y
  • Nếu nó trả về 0: x == y
  • Nếu nó trả về một số âm: x

Tuy nhiên,

>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7 nhận được một tham số, tính toán kết quả và sau đó sử dụng tính toán để sắp xếp và so sánh. Điều này có nghĩa là trong Python 2, bạn có thể sắp xếp một danh sách các số theo giá trị khối của chúng theo hai cách khác nhau:

>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]

Trong Python 3, tham số

>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 đã bị xóa, chủ yếu vì hai lý do.

Đầu tiên, mọi thứ được thực hiện với

>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 có thể được thực hiện với
>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7. Thứ hai,
>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7 nhanh hơn
>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1. Khi
>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 được truyền dưới dạng tham số, thuật toán sắp xếp so sánh các cặp giá trị và hàm so sánh được gọi là nhiều lần cho mỗi mục.

Mặt khác, khóa chỉ thực hiện tính toán một lần. Do đó, sự phức tạp được giảm. Điều này làm cho mã ít bị lỗi, vì cú pháp được đơn giản hóa. .

Nếu bạn quen thuộc với Java hoặc C ++, bạn có thể quen thuộc với

>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 hơn
>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7. Trên thực tế, trong Python 3, bạn có thể sử dụng
>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 với
>>> import functools

>>> l = [6, 8, 10, 23, -4, -7]

>>> def compare(x, y):
...    return x ** 3 - y ** 3

>>> sorted_l = sorted(l, key=functools.cmp_to_key(compare))
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
4, sẽ chuyển đổi
>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 thành
>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7. Hãy khám phá điều này nhiều hơn trong phần tiếp theo.

Các chức năng sắp xếp tùy chỉnh trong Python với functools.cmp_to_key (Func)

functools.cmp_to_key (FUNC) được sử dụng để chuyển đổi hàm so sánh kiểu cũ thành hàm chính. Nó có sẵn trong Python 2.7, Python 3.2 và sau đó.

Theo tài liệu Python 3, hàm so sánh là bất kỳ khả năng gọi nào chấp nhận hai đối số, so sánh chúng và trả về một số âm cho ít hơn, bằng không về bình đẳng hoặc số dương cho lớn hơn. Hàm

>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7 là một hàm có thể gọi được chấp nhận một đối số và trả về một giá trị khác được sử dụng làm loại
>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7.

Trước Python 2.4, không có Sắp xếp () và list.sort () & nbsp; Không có đối số từ khóa. Thay vào đó, Python 2 đã hỗ trợ tham số

>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 để xử lý các hàm so sánh do người dùng chỉ định.

Khi chuyển mã từ Python 2 sang Python 3, bạn có thể phải chuyển đổi hàm từ

>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 thành
>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7. Trong Python 3,
>>> import functools

>>> l = [6, 8, 10, 23, -4, -7]

>>> def compare(x, y):
...    return x ** 3 - y ** 3

>>> sorted_l = sorted(l, key=functools.cmp_to_key(compare))
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
4 đã được giới thiệu để tạo điều kiện cho quá trình này.

Chúng tôi sẽ sử dụng

>>> import functools

>>> l = [6, 8, 10, 23, -4, -7]

>>> def compare(x, y):
...    return x ** 3 - y ** 3

>>> sorted_l = sorted(l, key=functools.cmp_to_key(compare))
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
4 với các chức năng chấp nhận các chức năng chính như
>>> pokemon = [
...    ('Charmander', 'Fire', 52),
...    ('Blastoise', 'Water', 83),
...    ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])   # sort by attack power
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]
0 hoặc
from functools import cmp_to_key

def compare(pair1, pair2):
	number1, word1 = pair1
	number2, word2 = pair2
	if number1 == number2:
		if word1 < word2:
			return -1
		else:
			return 1
	if number1 < number2:
		return -1
	else:
		return 1

compare_key = cmp_to_key(compare)
5, mà tôi đã nói trong bài viết trước của tôi. Sử dụng ví dụ trước của chúng tôi để sắp xếp các số theo giá trị khối của chúng, bạn có thể viết hàm
>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 tùy chỉnh như sau:

>>> import functools

>>> l = [6, 8, 10, 23, -4, -7]

>>> def compare(x, y):
...    return x ** 3 - y ** 3

>>> sorted_l = sorted(l, key=functools.cmp_to_key(compare))
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]

Đôi khi, sử dụng khóa có thể ít rõ ràng hơn

>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1. Trong trường hợp này, có thể tốt hơn là sử dụng
>>> import functools

>>> l = [6, 8, 10, 23, -4, -7]

>>> def compare(x, y):
...    return x ** 3 - y ** 3

>>> sorted_l = sorted(l, key=functools.cmp_to_key(compare))
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
4, vì nó có thể dễ đọc và trực quan hơn.

Ví dụ, trong năm ngoái, Matur Matura (một kỳ thi Ba Lan tương tự như A, Abitur hoặc Baccalauréat), phần CNTT tùy chọn có một bài tập bao gồm điều này:

Cặp (Số1, Word1) nhỏ hơn cặp (Số 2, Word2) IF:smaller than pair (number2, word2) if:

  • Số1

Or:

  • Number1 == number2 và word1 nhỏ hơn bảng chữ cái so với word2.

Ví dụ, cặp (1, BBBB) nhỏ hơn cặp (2, AAA), nhưng cặp (3, AAA) nhỏ hơn cặp (3, AB).

Nói cách khác, chúng tôi muốn cặp được sắp xếp theo thứ tự tăng dần trên phần tử thứ nhất và phần tử thứ hai.

Do đó, chúng tôi hy vọng các cặp sẽ được trả lại theo thứ tự sau: & nbsp; (1, BBBB), (2, AAA), (3, AAA), (3, AB).(1, bbbb), (2, aaa), (3, aaa), (3, ab).

Dưới đây là hàm

>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 tùy chỉnh để giải quyết vấn đề này:

from functools import cmp_to_key

def compare(pair1, pair2):
	number1, word1 = pair1
	number2, word2 = pair2
	if number1 == number2:
		if word1 < word2:
			return -1
		else:
			return 1
	if number1 < number2:
		return -1
	else:
		return 1

compare_key = cmp_to_key(compare)

Nhưng ngay cả trong trường hợp này, chúng ta có thể giải quyết vấn đề với

>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7 bằng cách sắp xếp một danh sách các bộ dữ liệu:

>>> # List of tuples
>>> l = [(3, 'aaa'), (1, 'bbbb'), (3, 'ab'), (2, 'aaa')]

>>> # Sort with key on first and second element of each tuple
>>> sorted(l, key = lambda x: (x[0], x[1])) 
[(1, 'bbbb'), (2, 'aaa'), (3, 'aaa'), (3, 'ab')]

Chúng ta cũng có thể cố gắng làm cho vấn đề trở nên khó khăn hơn bằng cách sắp xếp yếu tố đầu tiên theo thứ tự giảm dần và phần thứ hai theo thứ tự tăng dần. Một lần nữa, chúng ta có thể giải quyết nó bằng

>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7:

>>> # Sort number in descending order and word in ascending order
>>> sorted(l, key = lambda x: (-x[0], x[1]))
[(3, 'aaa'), (3, 'ab'), (2, 'aaa'), (1, 'bbbb')]

Giả sử chúng ta xoay chuyển vấn đề theo cách khác, với yếu tố đầu tiên theo thứ tự tăng dần và thứ hai theo thứ tự giảm dần. Trong trường hợp này, việc vượt qua tham số

>>> # List of tuples
>>> l = [(3, 'aaa'), (1, 'bbbb'), (3, 'ab'), (2, 'aaa')]

>>> # Sort with key on first and second element of each tuple
>>> sorted(l, key = lambda x: (x[0], x[1])) 
[(1, 'bbbb'), (2, 'aaa'), (3, 'aaa'), (3, 'ab')]
2 là
>>> # List of tuples
>>> l = [(3, 'aaa'), (1, 'bbbb'), (3, 'ab'), (2, 'aaa')]

>>> # Sort with key on first and second element of each tuple
>>> sorted(l, key = lambda x: (x[0], x[1])) 
[(1, 'bbbb'), (2, 'aaa'), (3, 'aaa'), (3, 'ab')]
3 sẽ giải quyết nó.

>>> # Sort number in ascending order and word in descending order
>>> sorted(l, key = lambda x: (-x[0], x[1]), reverse=True)
[(1, 'bbbb'), (2, 'aaa'), (3, 'ab'), (3, 'aaa')]

Thật khó khăn khi tìm thấy một trường hợp

>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 không thể được thay thế bằng
>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7. Bởi vì hiệu suất
>>> import functools

>>> l = [6, 8, 10, 23, -4, -7]

>>> def compare(x, y):
...    return x ** 3 - y ** 3

>>> sorted_l = sorted(l, key=functools.cmp_to_key(compare))
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
4 rất chậm so với
>>> class Pokemon:
...    def __init__(self, name, category, attack):
...        self.name = name
...        self.category = category
...        self.attack = attack
...    def __repr__(self):
...        return repr((self.name, self.category, self.attack))



>>> pokemon_objects = [
...    Pokemon('Beedrill', 'Poison', 90),
...    Pokemon('Charmander', 'Fire', 52),
...    Pokemon('Blastoise', 'Water', 83),
...            ]
>>> sorted(pokemon_objects, key=lambda x: x.attack)   # sort by attack
[('Charmander', 'Fire', 52),
 ('Blastoise', 'Water', 83),
 ('Beedrill', 'Poison', 90)]

7, nên nó chỉ nên được sử dụng như là phương sách cuối cùng để thực hiện chức năng sắp xếp tùy chỉnh trong Python.

Nếu bạn muốn biết thêm về các chức năng ánh xạ, hãy xem bài viết của tôi trên Filter (), map () và giảm ().

Đóng suy nghĩ về các chức năng sắp xếp tùy chỉnh trong Python

Trong bài viết này, chúng tôi đã khám phá cách thực hiện các chức năng sắp xếp và so sánh tùy chỉnh trong Python. Chúng tôi đã học được một chút lịch sử Python và cố gắng hiểu các lựa chọn được thực hiện với

>>> l = [6, 8, 10, 23, -4, -7]
>>> # The cmp parameter has been removed in Python 3
>>> sorted_l = sorted(l, cmp=lambda x, y: x ** 3 - y ** 3) # Sort with cmp
>>> sorted_l = sorted(l, key=lambda x: x ** 3) # Sort with key
>>> print(sorted_l)
[-7, -4, 6, 8, 10, 23]
1 và chìa khóa giữa Python 2 và 3 để thực hiện các chức năng sắp xếp tùy chỉnh trong Python.

Để hiểu rõ hơn các khái niệm được giải thích trong các bài viết này, luôn luôn là một ý tưởng tốt để chơi với đoạn mã và xây dựng các ví dụ của riêng bạn.

Cuối cùng, nếu bạn muốn tìm hiểu thêm về thao tác dữ liệu trong Python, hãy thoải mái kiểm tra bài viết tuyệt vời của Yigit, về cách lọc hàng và chọn các cột trong khung dữ liệu Python với gấu trúc.

Và nếu bạn muốn đưa mọi thứ lên một tầm cao mới, hãy thử bài hát Python for Data Science của chúng tôi. Học hỏi!

Cách nhanh nhất để sắp xếp một danh sách trong Python là gì?

Để tóm tắt lại thí nghiệm của chúng tôi, đây là các thuật toán sắp xếp hàng đầu trong Python được xếp hạng nhanh nhất đến chậm nhất, được làm tròn đến thứ một hàng ngàn gần nhất:..
Sắp xếp tích hợp của Python: 0,009s ..
Sắp xếp radix: 0,220s ..
Quicksort: 0,247s ..
Sắp xếp vỏ: 0,250s ..
Sắp xếp hợp nhất: 0,435s ..
Sắp xếp đống: 0,473s ..
Đếm loại: 1.945s ..
Lựa chọn: 3.426s ..

Làm thế nào để sắp xếp () hoạt động trong Python?

Hàm python sort () hàm Sắp xếp () Trả về một danh sách được sắp xếp của đối tượng có thể lặp lại được chỉ định.Bạn có thể chỉ định thứ tự tăng dần hoặc giảm dần.Chuỗi được sắp xếp theo thứ tự bảng chữ cái, và các số được sắp xếp bằng số.Lưu ý: Bạn không thể sắp xếp một danh sách chứa cả giá trị chuỗi và giá trị số.returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.