Python Data Structures and Common Operations | Python数据结构与常用操作

📚 Python Data Structures and Common Operations | Python数据结构与常用操作

Data structures are the backbone of Python programming. In a computer science exam, you must be able to explain how lists, tuples, strings, dictionaries and sets behave, and which operations are efficient. This article reviews the essential Python data structures, their mutability, common methods and typical time complexities, with paired English and Chinese explanations for revision.

数据结构是 Python 编程的核心。在计算机科学考试中,你必须能够解释列表、元组、字符串、字典和集合的行为,并了解哪些操作是高效的。本文复习 Python 的核心数据结构、它们的可变性、常用方法及典型时间复杂度,以中英对照的方式帮助你备考。

1. Why Data Structures Matter | 为什么数据结构重要

A data structure is an organised way of storing and accessing data. Python provides several built-in types, each with different strengths. The choice of structure can affect memory use, speed and readability.

数据结构是有组织地存储和访问数据的方式。Python 提供了多个内置类型,各自有不同优势。选择合适的数据结构会影响内存使用、运行速度和代码可读性。

In exam questions, you may be asked to choose the best structure for a task. For example, use a list when you need ordered access, a dictionary when you need fast lookup by key, a set when you need to remove duplicates, and a tuple when the data should not change.

在考试题目中,你可能会被要求为某个任务选择最佳数据结构。例如,需要有序访问时用列表;需要按键快速查找时用字典;需要去重时用集合;当数据不应改变时用元组。


2. Lists: Dynamic Arrays | 列表:动态数组

Lists are ordered, mutable sequences. They may contain elements of different types, and they allow duplicate values. A list stores references to objects, so the same object may appear more than once.

列表是有序、可变的序列。列表可以包含不同类型的元素,也允许重复值。列表存储对象的引用,因此同一个对象可能出现多次。

Common operations include append, insert, remove, pop, index, count, slicing and sorting. Index access by position is O(1), but inserting or deleting from the middle is O(n).

常见操作包括 appendinsertremovepopindexcount、切片和排序。按位置访问是 O(1),但从中间插入或删除是 O(n)。

fruits = ['apple', 'banana', 'cherry']
fruits.append('date')          # add to end
fruits.insert(1, 'blueberry')  # insert at index 1
first = fruits[0]              # O(1) index access
removed = fruits.pop()         # remove and return last item
del fruits[0]                  # remove by index
print(fruits)

Because lists are mutable, you can change an element with my_list[i] = value. This is often tested together with the idea of aliasing and copying, which is covered later.

由于列表是可变的,你可以使用 my_list[i] = value 修改元素。这一点常与别名和拷贝的概念一起考查,后文会详细说明。


3. Tuples: Immutable Sequences | 元组:不可变序列

Tuples are ordered sequences similar to lists, but they are immutable. Once created, a tuple cannot be changed. This makes tuples hashable when all of their elements are also immutable, so they can be used as dictionary keys.

元组是与列表类似的有序序列,但元组是不可变的。元组一旦创建,就无法修改。当元组中的所有元素都是不可变类型时,元组是可哈希的,因此可以用作字典的键。

Tuples support indexing, slicing, count, index and unpacking. Unpacking is a convenient way to assign separate variables from a tuple.

元组支持索引、切片、countindex 和解包。解包是一种将元组中元素分别赋值给多个变量的便捷方式。

point = (3, 4)
x, y = point
print(point[1])          # 4
# point[1] = 5          # TypeError: 'tuple' object does not support item assignment

Use tuples for fixed records such as coordinates, RGB colours or return values. In advanced use, collections.namedtuple creates tuple-like objects with named fields, which improves readability.

元组适合表示固定记录,例如坐标、RGB 颜色或函数返回值。在进阶用法中,collections.namedtuple 可以创建带字段名的元组类对象,提高代码可读性。


4. Strings: Immutable Character Sequences | 字符串:不可变字符序列

Strings are immutable sequences of characters. They behave like tuples for sequences, but they have many text-processing methods. In Python 3, strings are Unicode by default.

字符串是字符的不可变序列。在序列行为上,字符串类似于元组,但它有大量文本处理方法。在 Python 3 中,字符串默认使用 Unicode 编码。

Key methods include split, join, strip, lower, upper, replace, find, count and startswith. Slicing works exactly as with lists.

关键方法包括 splitjoinstriplowerupperreplacefindcountstartswith。切片操作与列表完全相同。

word = "algorithm"
print(word[::-1])                 # mhtirogla
parts = "a,b,c".split(",")        # ['a', 'b', 'c']
new = "  hello  ".strip().upper() # 'HELLO'
print(", ".join(["a", "b", "c"])) # a, b, c

Because strings are immutable, repeated concatenation in a loop can be slow. If you must combine many pieces, build a list and call ''.join(list) instead.

因为字符串是不可变的,在循环中反复拼接字符串可能很慢。如果需要合并大量片段,应先把片段放入列表,然后调用 ''.join(list) 进行拼接。


5. Dictionaries: Key-Value Maps | 字典:键值映射

Dictionaries store key-value pairs. Keys must be hashable, such as strings, numbers or tuples of immutable objects. Values may be of any type. In Python 3.7 and later, dictionaries preserve insertion order.

字典存储键值对。键必须是可哈希的,例如字符串、数字或包含不可变对象的元组。值可以是任意类型。在 Python 3.7 及更高版本中,字典会保留插入顺序。

The main power of a dictionary is fast lookup by key. Membership testing and retrieval are O(1) on average. Common methods are get, setdefault, update, pop, keys, values and items.

字典的主要优势是按键快速查找。平均情况下,成员检查和取值都是 O(1)。常用方法有 getsetdefaultupdatepopkeysvaluesitems

ages = {"Ali": 17, "Mia": 18}
ages["Bo"] = 19
age = ages.get("Ali", 0)          # returns 17, default if missing
for name, age in ages.items():
    print(name, age)

When counting items, a dictionary or collections.Counter is often useful. For example, you can count the frequency of characters in a string using a dictionary with get.

在统计次数时,字典或 collections.Counter 非常有用。例如,你可以使用带 get 的字典统计字符串中每个字符的出现次数。


6. Sets: Unique Elements and Set Operations | 集合:唯一元素与集合运算

A set is an unordered collection of unique hashable elements. Sets are mutable and support O(1) average membership testing. Storing duplicates in a set has no effect because each element can only appear once.

集合是无序且唯一元素的容器,元素必须可哈希。集合是可变的,平均情况下成员检查为 O(1)。由于集合中每个元素只能出现一次,所以重复存储不会生效。

Common set methods include add, remove, discard, union, intersection, difference and symmetric_difference. Operators such as |, &, - and ^ provide a shorter syntax.

常用集合方法包括 addremovediscardunionintersectiondifferencesymmetric_difference。运算符 |&-^ 提供了更简短的写法。

s = {1, 2, 3}
s.add(3)               # no duplicate added
t = {2, 3, 4}
print(s & t)           # {2, 3}
print(s | t)           # {1, 2, 3, 4}
print(s - t)           # {1}
print(s ^ t)           # {1, 4}

Use a set whenever you need to remove duplicates from a sequence or test membership quickly. However, sets do not support indexing or ordering, so you cannot access an element by position.

当你需要去除序列中的重复项或快速测试成员身份时,应使用集合。但集合不支持索引和顺序,因此不能按位置访问元素。


7. Mutability, Aliasing, and Copying | 可变性、别名与拷贝

In Python, assignment does not copy an object. When you write b = a for a list, both names point to the same object. This is called aliasing. Changing the list through one name affects the other.

在 Python 中,赋值不会复制对象。当你对列表执行 b = a 时,两个名字指向同一个对象,这称为别名。通过其中一个名字修改列表,另一个名字也会受到影响。

For immutable types such as strings and tuples, aliasing is less dangerous because the object cannot change. For mutable types such as lists, dictionaries and sets, you must decide whether you need a copy.

对于字符串和元组等不可变类型,别名问题相对安全,因为对象不能改变。对于列表、字典和集合等可变类型,你必须判断自己是否需要一份拷贝。

a = [1, 2, 3]
b = a                # alias, not a copy
b.append(4)
print(a)             # [1, 2, 3, 4]

c = a.copy()         # shallow copy
c.append(5)
print(a)             # [1, 2, 3, 4]

A shallow copy copies the container but not the nested objects. If the list contains other lists, the inner lists are still shared. Use copy.deepcopy to fully copy nested structures.

浅拷贝会复制外层容器,但不会复制嵌套对象。如果列表中包含其他列表,内部列表仍然共享。使用 copy.deepcopy 可以完整复制嵌套结构。


8. List Comprehensions and Generator Expressions | 列表推导式与生成器表达式

Comprehensions give a compact way to build lists, dictionaries and sets. The general form is [expression for item in iterable if condition]. They are common in exam-style code, so you must be able to trace and write them.

推导式提供了一种简洁地构建列表、字典和集合的方式。一般形式是 [expression for item in iterable if condition]。它们在考试代码中很常见,你必须能够追踪和编写它们。

A list comprehension creates a complete list in memory. If you only need to iterate once, use a generator expression with parentheses () instead; it saves memory.

列表推导式会在内存中创建完整列表。如果只需要迭代一次,可以使用带圆括号的生成器表达式 (),这样更节省内存。

squares = [x * x for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
squares_dict = {x: x * x for x in range(5)}
unique_set = {x % 3 for x in range(10)}
total = sum(x * x for x in range(10))  # generator expression

Understanding comprehension order is important. The loop part is written from left to right in the same order as a normal nested loop. Exam questions often ask you to predict the output of a comprehension.

理解推导式的执行顺序非常重要。循环部分从左到右书写,和普通嵌套循环的顺序一致。考试题目经常要求你预测推导式的输出结果。


9. Common Operations and Complexity | 常用操作与复杂度

Time complexity is a frequent exam topic. The table below summarises the average complexity of common operations.

时间复杂度是常见的考试主题。下表总结了常见操作的平均复杂度。

Structure Operation Average Complexity
List Index access O(1)
List Append O(1) amortised
List Insert / delete middle O(n)
Tuple Index access O(1)
String Find / slice O(n)
Dict Get / set / delete by key O(1) average
Set Add / remove / membership O(1) average
List / Tuple Membership test with in O(n)

Remember that dictionary and set complexities depend on hash quality. In a good hash table, lookup is O(1), but in the worst case it can become O(n).

请记住,字典和集合的复杂度依赖于哈希质量。在良好的哈希表中,查找是 O(1),但最坏情况下可能退化为 O(n)。


10. Stacks and Queues with Collections | 用 collections 实现栈与队列

Stacks and queues are common abstract data types. In Python, a list can be used as a stack with append and pop, giving LIFO order.

栈和队列是常见的抽象数据类型。在 Python 中,列表可以用 appendpop 作为栈使用,遵循后进先出 LIFO 顺序。

For a queue, using pop(0) on a list is slow because shifting elements takes O(n). The collections.deque object supports fast appends and pops from both ends, so it is a better choice for a queue.

对于队列,在列表上使用 pop(0) 较慢,因为移动元素需要 O(n)。collections.deque 支持从两端快速添加和弹出元素,因此它更适合实现队列。

stack = []
stack.append('a')

Published by TutorHao | Computer Science Revision Series | aleveler.com

更多咨询请联系16621398022(同微信)

Comments

屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from aleveler.com

Subscribe now to keep reading and get access to the full archive.

Continue reading