杰瑞科技汇

sort python array

Of course! Sorting arrays in Python is a fundamental task. The term "array" can refer to a few different things in Python, so I'll cover the most common ones: lists (the standard Python sequence), NumPy arrays, and arrays from the array module.

Here’s a complete guide, from the simplest methods to more advanced sorting techniques.


Sorting Python Lists (Most Common)

Lists are the most common "array-like" structure in Python. Python provides two primary ways to sort them:

A) The list.sort() Method (In-place)

This method modifies the original list directly and returns None.

numbers = [4, 2, 9, 1, 5, 6, 8, 3, 7]
# Sort the list in ascending order
numbers.sort()
print(f"Sorted list (ascending): {numbers}")
# Output: Sorted list (ascending): [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Sort the list in descending order
numbers.sort(reverse=True)
print(f"Sorted list (descending): {numbers}")
# Output: Sorted list (descending): [9, 8, 7, 6, 5, 4, 3, 2, 1]

Key Characteristics:

  • In-place: It changes the original list.
  • Returns None: A common mistake is to assign the result to a new variable.
    my_list = [3, 1, 2]
    new_list = my_list.sort() # This is incorrect!
    print(f"my_list: {my_list}")   # Output: my_list: [1, 2, 3]
    print(f"new_list: {new_list}") # Output: new_list: None

B) The sorted() Built-in Function (Creates a New List)

This function takes any iterable (like a list) and returns a new, sorted list, leaving the original list unchanged.

numbers = [4, 2, 9, 1, 5, 6, 8, 3, 7]
# Create a new sorted list in ascending order
sorted_numbers_asc = sorted(numbers)
print(f"New sorted list (ascending): {sorted_numbers_asc}")
# Output: New sorted list (ascending): [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(f"Original list is unchanged: {numbers}")
# Output: Original list is unchanged: [4, 2, 9, 1, 5, 6, 8, 3, 7]
# Create a new sorted list in descending order
sorted_numbers_desc = sorted(numbers, reverse=True)
print(f"New sorted list (descending): {sorted_numbers_desc}")
# Output: New sorted list (descending): [9, 8, 7, 6, 5, 4, 3, 2, 1]

Key Characteristics:

  • Not in-place: The original list is preserved.
  • Returns a new list: This is the safest and most flexible method.

Advanced Sorting: The key Argument

Both list.sort() and sorted() accept a key argument. This is a powerful feature that lets you specify a function to be called on each element prior to making comparisons.

Example 1: Sorting a List of Tuples by a Specific Element

Imagine you have a list of students and their scores, and you want to sort them by score.

students = [
    ('Alice', 88),
    ('Bob', 95),
    ('Charlie', 72),
    ('David', 85)
]
# Sort by the second element of each tuple (the score)
# The lambda function tells sort to look at item[1]
sorted_by_score = sorted(students, key=lambda student: student[1])
print(sorted_by_score)
# Output: [('Charlie', 72), ('Alice', 88), ('David', 85), ('Bob', 95)]
# To sort in descending order by score
sorted_by_score_desc = sorted(students, key=lambda student: student[1], reverse=True)
print(sorted_by_score_desc)
# Output: [('Bob', 95), ('Alice', 88), ('David', 85), ('Charlie', 72)]

Example 2: Case-Insensitive Sorting of Strings

By default, Python sorts strings with uppercase letters before lowercase letters. The key argument can fix this.

words = ["Apple", "banana", "cat", "Dog", "elephant"]
# Default sort (A before a)
print(sorted(words))
# Output: ['Apple', 'Dog', 'banana', 'cat', 'elephant']
# Case-insensitive sort
print(sorted(words, key=lambda s: s.lower()))
# Output: ['Apple', 'banana', 'cat', 'Dog', 'elephant']

Example 3: Sorting by a Custom Object's Attribute

If you have a list of custom objects, you can sort them by an attribute.

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade
    def __repr__(self): # Helps print the object nicely
        return f"Student({self.name}, {self.grade})"
student_roster = [
    Student('Zoe', 92),
    Student('Amy', 95),
    Student('Mike', 88)
]
# Sort by the 'grade' attribute
sorted_by_grade = sorted(student_roster, key=lambda student: student.grade)
print(sorted_by_grade)
# Output: [Student(Mike, 88), Student(Zoe, 92), Student(Amy, 95)]

Sorting Other "Array" Types

A) NumPy Arrays

If you're working with numerical data, you're likely using the NumPy library. NumPy has its own highly efficient sorting functions.

import numpy as np
# Create a NumPy array
arr = np.array([4, 2, 9, 1, 5, 6, 8, 3, 7])
# Sort the array in-place (modifies the original array)
arr.sort()
print(f"NumPy array sorted in-place: {arr}")
# Output: NumPy array sorted in-place: [1 2 3 4 5 6 7 8 9]
# Create a new sorted array (leaves original unchanged)
arr2 = np.array([4, 2, 9, 1, 5])
sorted_arr2 = np.sort(arr2)
print(f"Original NumPy array: {arr2}")
print(f"New sorted NumPy array: {sorted_arr2}")
# Output:
# Original NumPy array: [4 2 9 1 5]
# New sorted NumPy array: [1 2 4 5 9]

NumPy also offers more advanced sorting like argsort (which returns the indices that would sort the array) and sorting along specific axes in multi-dimensional arrays.

B) Arrays from the array Module

Python has a built-in array module that creates more memory-efficient arrays than lists, but they are less flexible. It works very similarly to lists.

import array
# Create an array of integers
arr = array.array('i', [4, 2, 9, 1, 5, 6, 8, 3, 7])
# The array object has its own sort() method (in-place)
arr.sort()
print(f"array module array sorted: {arr}")
# Output: array module array sorted: array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
# You can also use the sorted() function to create a new list
arr2 = array.array('i', [4, 2, 9])
sorted_list_from_arr = sorted(arr2) # This returns a regular Python list
print(f"New list from sorted array: {sorted_list_from_arr}")
# Output: New list from sorted array: [2, 4, 9]

Summary: Which One Should I Use?

Method Use Case Key Feature
sorted(my_list) Most common use case. When you need a new sorted list and want to keep the original. Returns a new sorted list. Original is safe.
my_list.sort() When you are sure you want to modify the list in-place and don't need the original order anymore. Can be slightly more memory-efficient for very large lists. Modifies the list in-place. Returns None.
key=... When sorting is not based on the element's natural value (e.g., by a tuple's second item, case-insensitively, or by an object's attribute). Extremely powerful for custom sorting logic.
np.sort() / arr.sort() When working with NumPy arrays for numerical or scientific computing. Highly optimized for performance on large numerical datasets.
分享:
扫描分享到社交APP
上一篇
下一篇