杰瑞科技汇

Python有序列表如何实现与使用?

Of course! In Python, the term "ordered list" can refer to a few different things depending on the context. Let's break it down, from the most common built-in type to more specialized data structures.

Python有序列表如何实现与使用?-图1
(图片来源网络,侵删)

The Built-in list: An Ordered, Mutable Collection

This is what most Python developers mean when they talk about a list. A Python list is:

  • Ordered: Elements are stored in a specific sequence. The order you add items is the order they stay in.
  • Mutable: You can change its contents after it's created (add, remove, or modify elements).
  • Allows Duplicates: You can have the same value multiple times.

This order is guaranteed and is a fundamental feature of the list type.

How Order is Maintained

The order is maintained by the index of each element. The first element is at index 0, the second at 1, and so on.

Example

# Create a list. The order is preserved.
fruits = ['apple', 'banana', 'cherry', 'date']
# Access elements by their index (position)
print(f"First fruit: {fruits[0]}")       # Output: First fruit: apple
print(f"Last fruit: {fruits[-1]}")        # Output: Last fruit: date
# Iterate over the list. The items will be printed in order.
print("\nIterating through the list:")
for fruit in fruits:
    print(fruit)
# Output:
# Iterating through the list:
# apple
# banana
# cherry
# date
# You can add to the end, and the order is maintained
fruits.append('elderberry')
print(f"\nList after appending: {fruits}")
# Output: List after appending: ['apple', 'banana', 'cherry', 'date', 'elderberry']
# You can insert at a specific position
fruits.insert(1, 'blueberry')
print(f"List after inserting at index 1: {fruits}")
# Output: List after inserting at index 1: ['apple', 'blueberry', 'banana', 'cherry', 'date', 'elderberry']

The collections.OrderedDict: An Ordered Dictionary

Sometimes you want a dictionary where the key-value pairs are remembered in the order they were inserted. Before Python 3.7, standard dictionaries did not guarantee this order. OrderedDict was the solution.

Python有序列表如何实现与使用?-图2
(图片来源网络,侵删)
  • Key Feature: Maintains insertion order of keys.
  • Use Case: Useful when you need to process items in a specific sequence, especially in older Python versions (<3.7).

Example

from collections import OrderedDict
# Create an OrderedDict. The order of insertion is preserved.
student_grades = OrderedDict()
student_grades['Alice'] = 95
student_grades['Bob'] = 88
student_grades['Charlie'] = 92
# Iterate through the items. They will appear in insertion order.
print("Student Grades (in order of insertion):")
for name, grade in student_grades.items():
    print(f"{name}: {grade}")
# Output:
# Student Grades (in order of insertion):
# Alice: 95
# Bob: 88
# Charlie: 92

Note: Since Python 3.7, the built-in dict also preserves insertion order. So, for modern Python, a regular dict is often sufficient. OrderedDict is still useful if you need to move items to the end or beginning efficiently or for compatibility with older code.


The array Module: A Compact, Ordered List

The built-in list is very flexible because it can hold items of different types. This flexibility comes with some memory overhead. The array module provides a more memory-efficient list-like structure that is ordered but requires all elements to be of the same numeric type.

  • Key Feature: Compact, ordered list of a single numeric type.
  • Use Case: When you need to store large sequences of numbers (e.g., for numerical or scientific computing) and want to save memory.

Example

import array
# Create an array of integers (signed 'i')
# The first argument is the type code, the second is the initial list
numbers = array.array('i', [10, 20, 30, 40, 50])
print(f"Array: {numbers}")
print(f"Type of array: {type(numbers)}")
# Access elements just like a list
print(f"First number: {numbers[0]}")
# Arrays are ordered and mutable
numbers.append(60)
print(f"Array after appending: {numbers}")
# Output: Array after appending: array('i', [10, 20, 30, 40, 50, 60])

Third-Party Libraries: sortedcontainers

For advanced use cases where you need a list that is always sorted, the sortedcontainers library is an excellent choice. It's highly optimized and provides three main ordered list types:

  • SortedList: A list that maintains elements in sorted order. Insertions are O(log n).
  • OrderedSet: A set that maintains insertion order (like a Python 3.7+ dict with only keys).
  • OrderedDict: A more performant version than the one in the standard library.

You need to install it first: pip install sortedcontainers

Python有序列表如何实现与使用?-图3
(图片来源网络,侵删)

Example: SortedList

# Make sure to install: pip install sortedcontainers
from sortedcontainers import SortedList
# Create a SortedList. It will be kept in sorted order.
# Note: It does NOT preserve the original insertion order.
sl = SortedList([5, 2, 8, 1, 9])
print(f"Initial SortedList: {list(sl)}")
# Output: Initial SortedList: [1, 2, 5, 8, 9]
# Add new items. The list remains sorted.
sl.add(4)
sl.update([0, 6])
print(f"List after adding/updating: {list(sl)}")
# Output: List after adding/updating: [0, 1, 2, 4, 5, 6, 8, 9]
# You can efficiently find elements in a large list
print(f"Index of 5: {sl.index(5)}")
# Output: Index of 5: 4

Summary Table

Data Structure Order Type Mutable? Key Use Case
list Insertion Order Yes The default, go-to ordered collection for most tasks.
dict (Python 3.7+) Insertion Order Yes When you need key-value pairs and care about the order they were added.
collections.OrderedDict Insertion Order Yes For older Python versions or when you need specific dict movement methods.
array.array Insertion Order Yes Storing large, homogeneous sequences of numbers to save memory.
SortedList Sorted Order Yes When you need a list that is always kept in sorted, ascending order.

Which One Should I Use?

  • For 99% of cases, use the built-in list. It's simple, fast, and does exactly what you need for an ordered, mutable collection.
  • If you need key-value pairs and care about the order they were added, use a dict (Python 3.7+).
  • If you are working with very large amounts of numerical data and memory is a concern, consider the array module.
  • If you need a list that is always sorted and you are doing frequent insertions, the sortedcontainers library is a fantastic choice.
分享:
扫描分享到社交APP
上一篇
下一篇