杰瑞科技汇

Python中sequence如何高效操作?

Of course! The term "sequence" in Python refers to a fundamental data structure that is an ordered collection of items. The order is important, and each item has a specific position, or index.

Let's break down sequences in Python, from the core concept to the specific types and common operations.

The Core Concept: What is a Sequence?

A sequence is an iterable container that supports three key features:

  1. Ordering: The elements are stored in a specific sequence, like a line of people. The first element, the second element, and so on.
  2. Indexing: You can access individual elements using their integer index, starting from 0 for the first element.
  3. Slicing: You can extract a sub-sequence (a "slice") by specifying a start and end index.

Think of it like a numbered list. You can point to item #3, or you can ask for items #5 through #10.


The Main Types of Sequences in Python

Python has several built-in data types that are sequences. They are broadly categorized into two groups: Mutable and Immutable.

  • Mutable: Can be changed after creation. You can add, remove, or modify elements.
  • Immutable: Cannot be changed after creation. Once created, it's fixed.

Here are the most common sequence types:

Type Category Description Example
list Mutable The most common sequence. A collection of items in square brackets []. Can hold items of different types. ['apple', 123, True]
tuple Immutable A fixed, ordered collection. Similar to a list but cannot be changed. Defined with parentheses . ('apple', 123, True)
str Immutable A sequence of Unicode characters (text). Defined with single or double quotes. "hello world"
range Immutable An efficient sequence of numbers, commonly used in for loops. Does not store all numbers in memory. range(10)
bytes Immutable A sequence of bytes, used for handling binary data. b'hello'
bytearray Mutable A mutable version of bytes. bytearray(b'hello')

Common Operations on All Sequences

These operations work for almost all sequence types, whether they are list, tuple, str, or range.

a) Accessing Elements by Index (Indexing)

Use square brackets [] with the index number. Python uses zero-based indexing.

my_list = ['a', 'b', 'c', 'd']
my_string = "hello"
# Get the first element (index 0)
print(my_list[0])  # Output: 'a'
# Get the third element (index 2)
print(my_string[2]) # Output: 'l'
# Negative indexing counts from the end
# -1 is the last element, -2 is the second to last, etc.
print(my_list[-1]) # Output: 'd'
print(my_string[-2]) # Output: 'l'

b) Slicing

Extract a portion of the sequence using the operator. The format is [start:stop:step]. The stop index is exclusive.

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get elements from index 2 up to (but not including) index 5
print(my_list[2:5])   # Output: [2, 3, 4]
# Get the first 4 elements
print(my_list[:4])    # Output: [0, 1, 2, 3]
# Get elements from index 5 to the end
print(my_list[5:])    # Output: [5, 6, 7, 8, 9]
# Get every second element (step of 2)
print(my_list[::2])   # Output: [0, 2, 4, 6, 8]
# Reverse the sequence (step of -1)
print(my_list[::-1])  # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

c) Getting the Length

Use the built-in len() function to find the number of items.

my_tuple = (10, 20, 30, 40)
my_string = "python"
print(len(my_tuple))  # Output: 4
print(len(my_string)) # Output: 6

d) Checking for Membership

Use the in keyword to check if an item exists in the sequence.

my_list = ['apple', 'banana', 'cherry']
print('apple' in my_list)  # Output: True
print('grape' in my_list)  # Output: False

e) Concatenation and Repetition

  • Joins two sequences together.
  • Repeats a sequence.
list1 = [1, 2]
list2 = [3, 4]
# Concatenation
print(list1 + list2) # Output: [1, 2, 3, 4]
# Repetition
print(list1 * 3)     # Output: [1, 2, 1, 2, 1, 2]
# Works for strings too
print("hi" + " there") # Output: hi there
print("na" * 4)       # Output: nananana

Mutable vs. Immutable: A Crucial Difference

This is the most important distinction when working with sequences.

Mutable Example: list

You can change, add, or remove elements after the list is created.

my_list = ['a', 'b', 'c']
# Change an element by index
my_list[1] = 'z'
print(my_list) # Output: ['a', 'z', 'c']
# Add an element to the end
my_list.append('d')
print(my_list) # Output: ['a', 'z', 'c', 'd']
# Remove an element
my_list.remove('z')
print(my_list) # Output: ['a', 'c', 'd']

Immutable Example: tuple

If you try to change a tuple, you will get a TypeError.

my_tuple = ('a', 'b', 'c')
# This will cause an error!
# my_tuple[1] = 'z'  # TypeError: 'tuple' object does not support item assignment
# You can't add or remove elements either.
# my_tuple.append('d') # AttributeError: 'tuple' object has no attribute 'append'

Why does this matter?

  • Use list when you need a collection that can change (e.g., a list of students in a class, a shopping cart).
  • Use tuple when you want a fixed collection of items that should not be changed (e.g., the coordinates of a point (x, y), the days of the week ('Mon', 'Tue', ...)). Tuples are also slightly faster and use less memory than lists.

When to Use Which Sequence?

Use Case Best Choice Why?
A collection of items that might change. list It's mutable and flexible.
A fixed collection of items, like coordinates or database records. tuple It's immutable, ensuring the data can't be accidentally changed.
Storing text. str It's the dedicated, immutable type for text.
Looping a specific number of times. range It's memory-efficient, as it doesn't store all numbers in memory.
A sequence where order doesn't matter, and you need fast lookups. set Note: A set is not a sequence because it's unordered. It's a different data structure (an unordered collection).

Example: Processing a Sequence

Let's say you have a list of student grades and you want to find the average of the top 3 scores.

grades = [88, 92, 75, 99, 60, 85, 91]
# 1. Sort the list in descending order
grades.sort(reverse=True)
print(f"Sorted grades: {grades}") # Output: Sorted grades: [99, 92, 91, 88, 85, 75, 60]
# 2. Slice the top 3 scores
top_three = grades[:3]
print(f"Top three scores: {top_three}") # Output: Top three scores: [99, 92, 91]
# 3. Calculate the average
average = sum(top_three) / len(top_three)
print(f"Average of top three: {average:.2f}") # Output: Average of top three: 94.00

This example demonstrates combining several sequence operations (sort, len, sum, slicing) to solve a common problem.

分享:
扫描分享到社交APP
上一篇
下一篇