Data Structures数据结构
Programs are not just sequences of instructions, they also need to organise data efficiently. A data structure is a way of arranging information in memory so that you can store, retrieve, and modify it quickly and clearly. This guide covers the foundational data structures you will use across every course: arrays and lists (ordered collections), indexing and traversal, list operations such as append and remove, two-dimensional arrays for grid and table data, dictionaries for key-value lookup, and tuples and sets for fixed or unique collections. Each section pairs pseudocode with Python and ends with guidance on when to choose one structure over another. Worked examples draw on topics from CSTA, AP CSP, Ontario ICS, BC, and Alberta CSE.程序不仅仅是指令序列,它们还需要高效地组织数据。data structure(数据结构)是在内存中排列信息的方式,使你能够快速清晰地存储、检索和修改数据。本指南涵盖你在每门课程中都会用到的基础数据结构:array(数组)和list(列表)(有序集合)、index(索引)与traversal(遍历)、列表操作(如追加和删除)、用于网格和表格数据的2D array(二维数组)、用于键值查找的dictionary(字典)、以及用于固定或唯一集合的tuple(元组)和set(集合)。每节内容均配有伪代码和 Python 对照,并以"何时选择哪种数据结构"的指导作结。例题均取材于 CSTA、AP CSP、安大略 ICS、BC 和阿尔伯塔 CSE 的相关主题。
Arrays and Lists数组与列表
- State the length of a list or array, its first and last valid index and its bounds.
- Access and change an element by index, including a negative index that counts from the end.
- Predict the result of a slice such as
temps[1:4], where the start is included and the stop is excluded. - Explain why an index outside the bounds raises an
IndexErrorat run time. - Distinguish a fixed-size array from a dynamic list and say when each name is used.
- 说出列表或数组的长度、第一个和最后一个有效索引,以及它的边界(
bounds)。 - 通过索引访问并修改元素,包括从末尾往回数的负索引。
- 预测切片(
slice)的结果,例如temps[1:4]:包含起点,不包含终点。 - 解释为什么超出边界的索引会在运行时引发
IndexError。 - 区分固定大小的数组与动态列表,并说明各自在什么场合使用这个名称。
- An array数组: a fixed-size, ordered collection of elements of the same type, stored in contiguous memory. Once created, the size does not change. Each element is identified by its index (position number). AB CSE2120 outcome 1.2.1: "the static array including: use of cells to store data, data homogeneity, use of an index (or indices) to identify the location of data elements.":固定大小的有序集合,元素类型相同,存储在连续内存中。创建后大小不变。每个元素通过索引(位置编号)标识。AB CSE2120 结果 1.2.1:"静态数组,包括:使用单元格存储数据、数据同质性、使用索引标识数据元素位置。"
- A list列表: a dynamic, ordered collection that can grow or shrink. In Python,
listis the built-in; in Java (AP CSA),ArrayListis the dynamic equivalent. CSTA 3A-AP-14: "Use lists to simplify solutions, generalizing computational problems instead of repeatedly using simple variables.":动态有序集合,可以增长或缩小。在 Python 中,list是内置类型;在 Java(AP CSA)中,ArrayList是动态等价物。CSTA 3A-AP-14:"使用列表简化解决方案,将计算问题泛化,而不是反复使用简单变量。"
An array of 5 integers: scores = [88, 74, 92, 65, 81]. Positions are zero-indexed in most languages (Python, Java, C). Index 0 holds 88; index 4 holds 81. The bounds of this array are 0 to 4 (length minus 1). Accessing index 5 would be an out-of-bounds error: checked automatically in Python/Java, silent corruption in C.含 5 个整数的数组:scores = [88, 74, 92, 65, 81]。大多数语言(Python、Java、C)中位置从零开始索引。索引 0 存储 88;索引 4 存储 81。该数组的边界为 0 到 4(长度减 1)。访问索引 5 会造成越界错误,Python/Java 自动检测,C 中则是静默内存损坏。
Worked Example 1: Declare, initialise, and access an array例题 1:声明、初始化并访问数组
Pseudocode and Python side by side.伪代码与 Python 对照。
# Pseudocode
DECLARE scores AS ARRAY OF 5 INTEGERS
SET scores TO [88, 74, 92, 65, 81]
OUTPUT scores[0] # first element: 88
OUTPUT scores[4] # last element: 81
以上伪代码说明:DECLARE 声明,ARRAY OF 数组,SET ... TO 赋值,OUTPUT 输出。Python translation below:
# Python
scores = [88, 74, 92, 65, 81]
print(scores[0]) # 88
print(scores[4]) # 81
print(len(scores)) # 5, the number of elements
In Python, len() gives the number of elements. The last valid index is always len(scores) - 1. Ontario ICS3U A1.5 requires students to describe elements, indexes, and bounds: these three terms are your vocabulary for any array question.在 Python 中,len() 返回元素数量。最后一个有效索引始终为 len(scores) - 1。安大略 ICS3U A1.5 要求学生描述元素、索引和边界,这三个术语是所有数组题目的词汇。
Worked Example 2: Negative indices, slices and IndexError例题 2:负索引、切片与 IndexError
Given temps = [15, 22, 18, 30, 27], find len(temps), temps[-1], temps[-5], the slices temps[1:4], temps[:2] and temps[3:], and say what temps[5] does.给定 temps = [15, 22, 18, 30, 27],求 len(temps)、temps[-1]、temps[-5]、切片 temps[1:4]、temps[:2] 和 temps[3:],并说明 temps[5] 会发生什么。
# Pseudocode
SET temps TO [15, 22, 18, 30, 27]
OUTPUT LENGTH(temps) # 5
OUTPUT temps[0] # 15 (first element)
OUTPUT temps[LENGTH(temps) - 1] # 27 (last element)
# Python
temps = [15, 22, 18, 30, 27]
print(len(temps)) # 5
print(temps[-1]) # 27
print(temps[-5]) # 15
print(temps[1:4]) # [22, 18, 30]
print(temps[:2]) # [15, 22]
print(temps[3:]) # [30, 27]
temps[2] = 19 # replace the element at index 2
print(temps) # [15, 22, 19, 30, 27]
print(temps[5]) # IndexError: list index out of range
A negative index -k means len(temps) - k: -1 is index 4 (value 27) and -5 is index 0 (value 15). A slice a:b takes indices a, a+1, ..., b-1, so 1:4 gives indices 1, 2, 3 (values 22, 18, 30), which is 4 - 1 = 3 elements. A missing start means 0 and a missing stop means len(temps). Assignment temps[2] = 19 changes the list in place.负索引 -k 表示 len(temps) - k:-1 是索引 4(值 27),-5 是索引 0(值 15)。切片 a:b 取索引 a、a+1、...、b-1,所以 1:4 取索引 1、2、3(值 22、18、30),共 4 - 1 = 3 个元素。省略起点表示 0,省略终点表示 len(temps)。赋值 temps[2] = 19 直接修改列表本身。
The valid indices are 0 to 4 (and -5 to -1). Index 5, or -6, is outside the bounds, so the last line stops the program with an IndexError. This is a run-time error: the code is well formed, but it asks for an element that does not exist. A slice such as temps[3:99] does not raise an error; it stops at the end of the list and gives [30, 27].有效索引是 0 到 4(以及 -5 到 -1)。索引 5 或 -6 超出边界,所以最后一行会让程序因 IndexError 而终止。这是运行时错误:代码格式没有问题,但它请求了一个不存在的元素。切片 temps[3:99] 则不会报错,它在列表末尾停止,结果是 [30, 27]。
temps with its indices. Positive indices (top) start at 0 and end at len(temps) - 1 = 4; negative indices (bottom) count back from the end, so temps[-1] is 27 and temps[-5] is 15. The shaded boxes are the slice temps[1:4]: it starts at index 1 and stops before index 4, so it holds 4 - 1 = 3 elements. Index 5 and index -6 are both outside the list and raise an IndexError.图 1. 列表 temps 及其索引。上方的正索引从 0 开始,到 len(temps) - 1 = 4 结束;下方的负索引从末尾往回数,因此 temps[-1] 是 27,temps[-5] 是 15。阴影方格是切片 temps[1:4]:从索引 1 开始,在索引 4 之前停止,所以含 4 - 1 = 3 个元素。索引 5 和索引 -6 都在列表之外,会引发 IndexError。temps = [15, 22, 18, 30, 27], what is the value of temps[2]?给定 temps = [15, 22, 18, 30, 27],temps[2] 的值是什么?Going deeper (CSTA 3B-AP-12: comparing data structures)深入(CSTA 3B-AP-12:比较数据结构)
CSTA 3B-AP-12 (Level 3B, grades 11-12) states: "Compare and contrast fundamental data structures and their uses. Examples could include strings, lists, arrays, stacks, and queues." At the HS level you are expected to know: (1) which structures are ordered vs. unordered; (2) which support O(1) access by index; (3) which support efficient insert/delete at arbitrary positions. Arrays excel at random access (index directly); they are poor at insertion in the middle (requires shifting). Linked lists (not covered here) excel at insertion but have O(n) access. This trade-off analysis is the 3B content.CSTA 3B-AP-12(3B 级,11-12 年级)指出:"比较和对比基本数据结构及其用途。示例可包括字符串、列表、数组、栈和队列。"在高中层面,你需要知道:(1) 哪些结构是有序的,哪些是无序的;(2) 哪些支持通过索引 O(1) 访问;(3) 哪些支持在任意位置高效插入/删除。数组擅长随机访问(直接索引);在中间插入表现差(需要移动元素)。链表(本指南不涵盖)擅长插入但访问时间为 O(n)。这种权衡分析是 3B 级内容。
Command words here are state (give the last valid index), trace (write what each line prints) and identify (name the error). Write the length first, then the last index as length minus 1, before you read any element. Common errors: treating len(list) as the last index, reading list[-1] as the second-last element, and forgetting that a slice stops before its end index. When asked for the error, name it: IndexError.
本节的指令词是 state(给出最后一个有效索引)、trace(写出每行输出)和 identify(指出错误)。读取任何元素之前,先写出长度,再写出最后一个索引 = 长度减 1。常见错误:把 len(list) 当成最后一个索引;把 list[-1] 当成倒数第二个元素;忘记切片在终点索引之前停止。被问到错误时要写出名称:IndexError。
A list has 8 elements. State its valid positive indices and its valid negative indices, and say what x[8] and x[-9] do.一个列表有 8 个元素。写出它的有效正索引和有效负索引,并说明 x[8] 和 x[-9] 会发生什么。
Positive indices are 0 to 7 and negative indices are -8 to -1. Both x[8] and x[-9] are outside the bounds, so each raises an IndexError.
正索引是 0 到 7,负索引是 -8 到 -1。x[8] 和 x[-9] 都超出边界,各自会引发 IndexError。
Given names = ["Ana", "Ben", "Chen", "Dia"], give names[-2], names[1:3] and names[:1].给定 names = ["Ana", "Ben", "Chen", "Dia"],求 names[-2]、names[1:3] 和 names[:1]。
names[-2] is index 2, so it is "Chen". names[1:3] takes indices 1 and 2, giving ["Ben", "Chen"]. names[:1] takes index 0 only, giving ["Ana"] (a list, not a string).
names[-2] 是索引 2,所以是 "Chen"。names[1:3] 取索引 1 和 2,结果是 ["Ben", "Chen"]。names[:1] 只取索引 0,结果是 ["Ana"](是列表,不是字符串)。
A program must store exactly 12 monthly totals that never change in number, and a separate collection of names that grows as people join. Which is better described as an array and which as a list?程序要存储恰好 12 个数量不会变化的月度总计,另外还要存储随人员加入而增长的姓名集合。哪一个更适合称为数组,哪一个更适合称为列表?
The 12 monthly totals fit a fixed-size array: the size is known and does not change. The names fit a dynamic list, because it must grow when people join (in Python both are a list).
12 个月度总计适合固定大小的数组:大小已知且不变。姓名集合适合动态列表,因为人员加入时它必须增长(在 Python 中两者都是 list)。
Trace this code and state what it prints: a = [4, 8, 15, 16], then a[1] = a[0] + a[3], then print(a[-1] - a[1]).追踪这段代码并写出输出:a = [4, 8, 15, 16],然后 a[1] = a[0] + a[3],然后 print(a[-1] - a[1])。
a[0] + a[3] is 4 + 16 = 20, so a becomes [4, 20, 15, 16]. Then a[-1] is 16 and a[1] is 20, so it prints 16 - 20 = -4.
a[0] + a[3] 是 4 + 16 = 20,所以 a 变成 [4, 20, 15, 16]。然后 a[-1] 是 16,a[1] 是 20,因此输出 16 - 20 = -4。
Indexing and Traversal索引与遍历
- Trace a
forloop over a list by element and by index, and choose the form that fits the task. - Write the accumulate, running-maximum and linear-search patterns, returning an index or -1 from a search.
- Use
range(start, stop)correctly, remembering that the stop value is excluded. - Locate an off-by-one error by tracing the first and last pass of a loop.
- Convert between a Python index (from 0) and an AP CSP list position (from 1).
- 追踪按元素和按索引遍历列表的
for循环,并选择适合任务的形式。 - 编写累加、滚动最大值和线性搜索(
linear search)模式,搜索时返回索引或 -1。 - 正确使用
range(start, stop),记住终点值不包含在内。 - 通过追踪循环的第一次和最后一次迭代,找出差一错误(
off-by-one)。 - 在 Python 索引(从 0 开始)与 AP CSP 列表位置(从 1 开始)之间互相换算。
- Indexing索引: accessing a single element by its position.
list[i]. Zero-based in Python/Java/C. One-based in AP CSP pseudocode notation. Out-of-range index raises an error.:通过位置访问单个元素。list[i]。Python/Java/C 中从零开始。AP CSP 伪代码表示法中从一开始。越界索引会引发错误。 - Traversal遍历: visiting every element in a collection exactly once, typically using a
forloop. Ontario ICS3U A2.3: "write algorithms with nested structures (e.g., to count elements in an array, calculate a total, find highest or lowest value, or perform a linear search).":恰好访问集合中每个元素一次,通常使用for循环。安大略 ICS3U A2.3:"编写带嵌套结构的算法(如计算数组中的元素、计算总和、找最高或最低值、或执行线性搜索)。"
Worked Example 3: Traversal patterns on a list of scores例题 3:对成绩列表的遍历模式
Given scores = [82, 74, 91, 68, 87], write pseudocode and Python for: (a) sum all scores; (b) find the highest score.给定 scores = [82, 74, 91, 68, 87],为以下任务编写伪代码和 Python:(a) 求所有成绩之和;(b) 找最高成绩。
(a) Sum: pseudocode and Python.(a) 求和:伪代码和 Python。
# Pseudocode
SET total TO 0
FOR EACH score IN scores:
SET total TO total + score
OUTPUT total # 402
# Python
scores = [82, 74, 91, 68, 87]
total = 0
for score in scores:
total += score
print(total) # 402
说明:FOR EACH 依次取每个元素;SET total TO total + score 累加。The accumulator pattern: initialise to 0, add each element one at a time.
(b) Maximum: pseudocode and Python.(b) 最大值:伪代码和 Python。
# Pseudocode
SET max_val TO scores[0]
FOR i FROM 1 TO LENGTH(scores) - 1:
IF scores[i] > max_val THEN
SET max_val TO scores[i]
OUTPUT max_val # 91
# Python
max_val = scores[0]
for i in range(1, len(scores)):
if scores[i] > max_val:
max_val = scores[i]
print(max_val) # 91
Note the use of index variable i to access scores[i]: this is index-based traversal as opposed to the element-based for score in scores used in (a). Both are correct; index-based is required when you need the position, not just the value.注意用索引变量 i 访问 scores[i],这是基于索引的遍历,与 (a) 中基于元素的 for score in scores 不同。两种都正确;当你需要位置而不仅仅是值时,必须使用基于索引的方式。
Worked Example 4: Linear search that returns an index or -1例题 4:返回索引或 -1 的线性搜索
Write a function that searches scores = [82, 74, 91, 68, 87] for a target and returns the index of the first match, or -1 if there is none. Trace the calls with targets 91 and 70, then give the AP CSP position of the match.编写一个函数,在 scores = [82, 74, 91, 68, 87] 中搜索目标值,返回第一个匹配项的索引;若没有则返回 -1。追踪目标为 91 和 70 的两次调用,并给出匹配项的 AP CSP 位置。
# Pseudocode
FUNCTION linear_search(values, target)
FOR i FROM 0 TO LENGTH(values) - 1
IF values[i] = target THEN
RETURN i
RETURN -1
# Python
def linear_search(values, target):
for i in range(len(values)):
if values[i] == target:
return i
return -1
scores = [82, 74, 91, 68, 87]
print(linear_search(scores, 91)) # 2
print(linear_search(scores, 70)) # -1
target = 91
i scores[i] scores[i] == 91 ?
0 82 False
1 74 False
2 91 True -> return 2, the loop stops
target = 70
i = 0, 1, 2, 3, 4 : every comparison is False
the loop ends -> return -1
For target 91 the function makes 3 comparisons and returns as soon as it finds a match, so the later elements are never read. For target 70 it makes all 5 comparisons and only then returns -1. In the worst case a linear search reads all n elements, which is O(n). In AP CSP pseudocode, which counts positions from 1, the match at Python index 2 is at position 3.目标为 91 时,函数做了 3 次比较,一找到匹配就立即返回,后面的元素不会被读取。目标为 70 时,函数做完全部 5 次比较,之后才返回 -1。最坏情况下线性搜索要读取全部 n 个元素,即 O(n)。在从 1 开始计位置的 AP CSP 伪代码中,Python 索引 2 处的匹配项位于位置 3。
Two common errors. First, return -1 must come after the loop: placed inside the loop, in an else beside the if, it would return -1 after the first mismatch. Second, range(len(values) + 1) makes the last pass use index 5, which raises an IndexError.两个常见错误。第一,return -1 必须放在循环之后:如果放在循环内部、if 旁边的 else 中,第一次不匹配就会返回 -1。第二,range(len(values) + 1) 会让最后一次迭代使用索引 5,从而引发 IndexError。
data = [10, 20, 30, 40, 50], what is the output of the following code? total = 0for i in range(0, 3): total += data[i]print(total)给定 data = [10, 20, 30, 40, 50],以下代码的输出是什么?total = 0for i in range(0, 3): total += data[i]print(total)range(0, 3) produces indices 0, 1, 2, so data[0]=10, data[1]=20, data[2]=30. Total = 10 + 20 + 30 = 60. Note that range(0, 3) excludes 3 (upper bound is exclusive in Python).range(0, 3) 产生索引 0、1、2,因此 data[0]=10、data[1]=20、data[2]=30。总和 = 10 + 20 + 30 = 60。注意 range(0, 3) 排除 3(Python 中上界是排他的)。range(0, 3) gives 0, 1, 2 only (not 3, 4). Only the first three elements are summed: 10+20+30=60.range(0, 3) 只给出 0、1、2(不包括 3、4)。只有前三个元素被求和:10+20+30=60。len(list) - 1 = 8 - 1 = 7. Accessing index 8 raises an IndexError.使用从零开始的索引,长度为 8 的列表索引为 0 到 7。最后一个有效索引始终为 len(list) - 1 = 8 - 1 = 7。访问索引 8 会引发 IndexError。Going deeper: AP CSP list notation (1-indexed)深入:AP CSP 列表表示法(从 1 开始索引)
AP CSP uses its own pseudocode reference sheet where lists are 1-indexed: the first element is at position 1 (not 0). So for scores ← [82, 74, 91, 68, 87], scores[1] is 82 and scores[5] is 87. The College Board pseudocode also uses LENGTH(list) for size and FOR EACH item IN list for traversal. When you see AP CSP exam questions using list notation, remember: 1-indexed, not 0-indexed.AP CSP 使用自己的伪代码参考手册,其中列表从 1 开始索引:第一个元素在位置 1(不是 0)。因此对于 scores ← [82, 74, 91, 68, 87],scores[1] 是 82,scores[5] 是 87。College Board 伪代码还使用 LENGTH(list) 表示大小,使用 FOR EACH item IN list 进行遍历。当你看到使用列表表示法的 AP CSP 考题时,记住:从 1 开始索引,不是从 0 开始。
Trace questions reward a trace table: one row per pass, showing the index and the value read. Check the first and the last pass against the bounds 0 and len(list) - 1, and remember that range(a, b) stops before b. When the question says write a search, state what it returns when nothing is found. Common errors: returning -1 inside the loop, looping to len(list) inclusive, and mixing the 0-based Python index with the 1-based AP CSP position.
Trace 类题目要写追踪表:每次迭代一行,写出索引和读到的值。把第一次和最后一次迭代与边界 0 和 len(list) - 1 对照检查,并记住 range(a, b) 在 b 之前停止。题目要求 write 搜索时,要写明找不到时返回什么。常见错误:在循环内部返回 -1;循环到 len(list)(含);把从 0 开始的 Python 索引与从 1 开始的 AP CSP 位置混淆。
With data = [10, 20, 30, 40, 50], what does for i in range(2, 5): print(data[i]) print?对于 data = [10, 20, 30, 40, 50],for i in range(2, 5): print(data[i]) 会输出什么?
range(2, 5) gives the indices 2, 3, 4 (the stop value 5 is excluded), so it prints 30, 40 and 50 on three lines.
range(2, 5) 给出索引 2、3、4(终点 5 不包含),所以分三行输出 30、40、50。
A student writes total = 0 then for i in range(1, len(data)): total += data[i] to add up data = [10, 20, 30, 40, 50]. What does it give, and how is it fixed?一名学生写了 total = 0,然后 for i in range(1, len(data)): total += data[i],想对 data = [10, 20, 30, 40, 50] 求和。结果是多少?如何修正?
It starts at index 1, so it skips data[0] and gives 20 + 30 + 40 + 50 = 140 instead of 150. Start at 0: range(len(data)), or loop directly with for value in data.
它从索引 1 开始,跳过了 data[0],得到 20 + 30 + 40 + 50 = 140,而不是 150。应从 0 开始:range(len(data)),或者直接用 for value in data 遍历。
For scores = [82, 74, 91, 68, 87], which Python index holds the element at AP CSP position 4, and what is its value?对于 scores = [82, 74, 91, 68, 87],AP CSP 位置 4 的元素对应哪个 Python 索引?它的值是多少?
AP CSP counts from 1 and Python from 0, so position 4 is Python index 3. scores[3] is 68.
AP CSP 从 1 开始计数,Python 从 0 开始,所以位置 4 对应 Python 索引 3。scores[3] 是 68。
Write a loop that counts how many values in scores = [82, 74, 91, 68, 87] are at least 80, and give the result.编写一个循环,统计 scores = [82, 74, 91, 68, 87] 中不小于 80 的值有多少个,并给出结果。
count = 0, then for s in scores: with if s >= 80: count += 1 inside. The values 82, 91 and 87 pass the test, so count is 3.
count = 0,然后 for s in scores:,循环体内写 if s >= 80: count += 1。82、91 和 87 通过测试,所以 count 是 3。
List Operations: Append, Insert, Remove列表操作:追加、插入、删除
- Use
append,insert,removeandpop, and state the list after each call. - Distinguish
remove(value)(by value) frompop(index)(by position, returns the element). - Explain how inserting or removing in the middle shifts the later elements.
- Explain aliasing:
b = agives one list two names, whilea.copy()makes a new list. - Name the error raised when
removeis given a value that is not in the list.
- 使用
append、insert、remove和pop,并写出每次调用后的列表。 - 区分
remove(value)(按值删除)与pop(index)(按位置删除,并返回该元素)。 - 解释在中间插入或删除元素时,后面的元素如何移动。
- 解释别名(
aliasing):b = a让一个列表有两个名字,而a.copy()会创建新列表。 - 说出
remove收到列表中不存在的值时引发的错误名称。
- Append追加: add an element to the end of a list. Pseudocode:
APPEND item TO list. Python:list.append(item). AB CSE2120 outcome 1.3.2: "inserting, deleting and replacing data.":在列表末尾添加元素。伪代码:APPEND item TO list。Python:list.append(item)。AB CSE2120 结果 1.3.2:"插入、删除和替换数据。" - Insert插入: add an element at a specific index, shifting later elements right. Python:
list.insert(index, item). Ontario ICS3U A3.3 (ICS4U): "create subprograms to insert and delete array elements.":在特定索引处添加元素,后面的元素向右移动。Python:list.insert(index, item)。安大略 ICS3U A3.3(ICS4U):"创建子程序以插入和删除数组元素。" - Remove删除: delete an element by value (first occurrence) or by index. Python:
list.remove(value)by value;list.pop(index)by index and returns the value.:按值(第一次出现)或按索引删除元素。Python:list.remove(value)按值删除;list.pop(index)按索引删除并返回该值。
Worked Example 5: Building and modifying a shopping list例题 5:构建和修改购物清单
Demonstrate all three operations on a list of strings.演示字符串列表上的全部三种操作。
# Pseudocode
DECLARE cart AS LIST
APPEND "apples" TO cart # cart = ["apples"]
APPEND "bread" TO cart # cart = ["apples", "bread"]
INSERT "milk" AT INDEX 1 IN cart # cart = ["apples", "milk", "bread"]
REMOVE "bread" FROM cart # cart = ["apples", "milk"]
OUTPUT LENGTH(cart) # 2
# Python
cart = []
cart.append("apples") # cart = ["apples"]
cart.append("bread") # cart = ["apples", "bread"]
cart.insert(1, "milk") # cart = ["apples", "milk", "bread"]
cart.remove("bread") # cart = ["apples", "milk"]
print(len(cart)) # 2
说明:append 末尾追加;insert(i, x) 在索引 i 处插入 x;remove(x) 删除第一个值为 x 的元素;len() 返回长度。Note: insert(1, "milk") pushes "bread" from index 1 to index 2: all elements at and after the insertion point shift right by 1.
Worked Example 6: Aliasing, copying and pop例题 6:别名、复制与 pop
Predict each printed line of the code below, then explain why a changes when only b was appended to, and why c does not.预测下面代码每一行的输出,然后解释为什么只对 b 做追加时 a 也会变化,而 c 不会。
# Pseudocode
SET a TO [3, 6, 9]
SET b TO a # b is another name for the same list
SET c TO COPY(a) # c is a new list with the same values
APPEND 12 TO b
SET x TO POP(a, 1) # remove index 1 and keep the value
# Python
a = [3, 6, 9]
b = a
c = a.copy()
b.append(12)
print(a) # [3, 6, 9, 12]
print(b) # [3, 6, 9, 12]
print(c) # [3, 6, 9]
print(a is b, a is c) # True False
x = a.pop(1)
print(x, a, b) # 6 [3, 9, 12] [3, 9, 12]
The assignment b = a copies the reference, not the list: a and b are two names for one list object, so the append through b is visible through a (Figure 2). The call a.copy() builds a new list holding the same values, so c is unaffected and stays [3, 6, 9]. The operator is tests whether two names refer to the same object.赋值 b = a 复制的是引用,而不是列表本身:a 和 b 是同一个列表对象的两个名字,因此通过 b 做的追加在 a 下也能看到(图 2)。调用 a.copy() 会创建一个值相同的新列表,所以 c 不受影响,仍是 [3, 6, 9]。运算符 is 用来判断两个名字是否指向同一个对象。
The call a.pop(1) removes the element at index 1 (the 6) and returns it, so x is 6. The elements after it shift one place left, giving [3, 9, 12], and because b is the same list it shows the same result. To make an independent copy use a.copy() or a[:]. Both copy only the top level, so lists nested inside a list are still shared.调用 a.pop(1) 删除索引 1 处的元素(即 6)并返回它,所以 x 是 6。它后面的元素左移一位,得到 [3, 9, 12];因为 b 是同一个列表,所以它显示相同的结果。要得到独立的副本,使用 a.copy() 或 a[:]。两者都只复制最外层,列表内部嵌套的列表仍然是共享的。
b = a and c = a.copy(), then b.append(12). The names a and b point to the same list object, so the appended 12 shows through both. The name c points to its own list, made before the append, so it still holds 3, 6, 9.图 2. 依次执行 b = a、c = a.copy() 和 b.append(12) 之后。名字 a 和 b 指向同一个列表对象,因此追加的 12 在两个名字下都能看到。名字 c 指向它自己的列表(在追加之前创建),所以仍是 3、6、9。nums?nums = [1, 2, 3, 4]nums.insert(2, 99)执行以下代码后,nums 是什么?nums = [1, 2, 3, 4]nums.insert(2, 99)insert(2, 99) places 99 at index 2. The original elements at indices 2, 3 shift right: [1, 2, 99, 3, 4]. Index 2 in the original list held 3; after insertion 99 is at 2 and 3 is at 3.insert(2, 99) 在索引 2 处插入 99。原来在索引 2、3 的元素向右移动:[1, 2, 99, 3, 4]。原列表中索引 2 存储 3;插入后 99 在索引 2,3 在索引 3。list.insert(i, x) inserts x before the element currently at index i. For [1,2,3,4] with insert(2, 99): 99 goes before index-2 element (which is 3), giving [1,2,99,3,4].list.insert(i, x) 在当前索引 i 的元素前插入 x。对 [1,2,3,4] 执行 insert(2, 99):99 插在索引 2 元素(即 3)之前,得 [1,2,99,3,4]。list.remove(value) finds the first element equal to value and removes it. list.pop(index) removes by index position (not value). del list[index] also removes by index. There is no list.delete() method in Python.list.remove(value) 找到第一个等于 value 的元素并删除它。list.pop(index) 按索引位置删除(不是按值)。del list[index] 也是按索引删除。Python 中没有 list.delete() 方法。remove(value) removes by value. pop(index) removes by position. Know the difference: exam questions often test this distinction.remove(value) 按值删除。pop(index) 按位置删除。了解区别,考题经常测试这一区别。State the contents of the list after each statement, and write the whole list every time rather than only the changed element. Remember that insert(i, x) places x at index i, remove(x) deletes the first match and raises a ValueError if there is none, and pop(i) returns the removed element (pop() with no argument removes the last). Common errors: believing that b = a makes a copy, and mixing up append (adds one element, even a list) with extend (adds each element of another list).
State 每条语句之后列表的内容,并且每次写出整个列表,而不是只写变化的元素。记住:insert(i, x) 把 x 放在索引 i,remove(x) 删除第一个匹配项,找不到时引发 ValueError,pop(i) 返回被删除的元素(不带参数的 pop() 删除最后一个)。常见错误:以为 b = a 会产生副本;把 append(添加一个元素,即使它本身是列表)与 extend(逐个添加另一个列表的元素)混淆。
Trace this code and give the final nums and x: nums = [1, 2, 3, 4], nums.insert(0, 9), nums.remove(3), x = nums.pop().追踪这段代码,给出最终的 nums 和 x:nums = [1, 2, 3, 4]、nums.insert(0, 9)、nums.remove(3)、x = nums.pop()。
After the insert: [9, 1, 2, 3, 4]. After remove(3): [9, 1, 2, 4]. Then pop() removes and returns the last element, so x is 4 and nums is [9, 1, 2].
插入之后:[9, 1, 2, 3, 4]。remove(3) 之后:[9, 1, 2, 4]。然后 pop() 删除并返回最后一个元素,所以 x 是 4,nums 是 [9, 1, 2]。
Starting from p = [3, 6, 9] and q = [3, 6, 9], find p after p.append([12, 15]) and q after q.extend([12, 15]), with the length of each.从 p = [3, 6, 9] 和 q = [3, 6, 9] 出发,求 p.append([12, 15]) 之后的 p 与 q.extend([12, 15]) 之后的 q,并给出各自的长度。
append adds the whole list as one element: p is [3, 6, 9, [12, 15]], length 4. extend adds each element: q is [3, 6, 9, 12, 15], length 5.
append 把整个列表作为一个元素加入:p 是 [3, 6, 9, [12, 15]],长度 4。extend 逐个加入元素:q 是 [3, 6, 9, 12, 15],长度 5。
What does [3, 6, 9].remove(100) do, and how can a program avoid the problem?[3, 6, 9].remove(100) 会发生什么?程序如何避免这个问题?
The value 100 is not in the list, so remove raises a ValueError. Test first with if 100 in lst: and call lst.remove(100) only when the test is true.
100 不在列表中,所以 remove 会引发 ValueError。先用 if 100 in lst: 测试,只有测试为真时才调用 lst.remove(100)。
Trace x = [1, 2], y = x, y = y + [3], print(x, y). Is x changed by the third statement?追踪 x = [1, 2]、y = x、y = y + [3]、print(x, y)。第三条语句会改变 x 吗?
It prints [1, 2] [1, 2, 3]. The expression y + [3] builds a new list and the name y is then re-pointed to it, so x is unchanged. Compare y.append(3), which would change the shared list and so change x as well.
输出 [1, 2] [1, 2, 3]。表达式 y + [3] 创建了新列表,名字 y 随后改为指向它,所以 x 不变。对比 y.append(3),它会修改共享的列表,因此 x 也会随之改变。
2D Arrays and Nested Lists Honors二维数组与嵌套列表 Honors
- Access an element of a 2D list with
grid[row][col]and state the number of rows and columns usinglen. - Write nested loops that visit every element, and that total one row or one column.
- Calculate row averages and column totals for a grid of scores.
- Build an empty grid safely and explain why
[[0] * 3] * 3gives three references to one row. - Sum the main diagonal of a square grid using
grid[i][i].
- 用
grid[row][col]访问二维列表的元素,并用len说出行数和列数。 - 编写嵌套循环访问每个元素,并对某一行或某一列求和。
- 对成绩网格计算每行的平均值和每列的总和。
- 安全地创建空网格,并解释为什么
[[0] * 3] * 3得到的是指向同一行的三个引用。 - 用
grid[i][i]对方阵的主对角线求和。
- Access访问:
grid[row][col]. Row first, column second. Think of it as "first pick the row (outer list), then pick the column (inner list).":grid[row][col]。先行,后列。把它想成"先选行(外层列表),再选列(内层列表)"。 - Nested loops嵌套循环: traverse a 2D structure with a loop inside a loop: the outer loop iterates rows, the inner loop iterates columns. Ontario ICS4U A3.5: "create algorithms to process elements in two-dimensional arrays.":用嵌套循环遍历二维结构:外层循环遍历行,内层循环遍历列。安大略 ICS4U A3.5:"创建处理二维数组元素的算法。"
Worked Example 7: A classroom grade grid例题 7:课堂成绩网格
3 students, 3 tests. Access and traverse the 2D array.3 名学生,3 次测试。访问并遍历二维数组。
# Pseudocode
DECLARE grades AS 2D ARRAY [3][3]
SET grades TO [[85, 90, 78],
[72, 88, 94],
[91, 67, 83]]
# Access student 0, test 1: grades[0][1]
OUTPUT grades[0][1] # 90
# Sum all grades
SET total TO 0
FOR row FROM 0 TO 2:
FOR col FROM 0 TO 2:
SET total TO total + grades[row][col]
OUTPUT total # 748
# Python
grades = [[85, 90, 78],
[72, 88, 94],
[91, 67, 83]]
print(grades[0][1]) # 90 (student 0, test 1)
total = 0
for row in grades:
for score in row:
total += score
print(total) # 748
说明:grades[row][col] 先选第 row 个内层列表,再从中取第 col 个元素。嵌套 for 循环遍历全部行列。The outer loop picks a row (a list of 3 scores); the inner loop picks each score in that row. This nested-loop pattern applies to any 2D structure: image pixels, game boards, distance matrices.
Worked Example 8: Row averages, column totals and the shared-row trap例题 8:行平均值、列总和与共享行陷阱
Using the grades grid of Worked Example 7 (3 students, 3 tests), (a) find each student's average to one decimal place, (b) find the total of each test, and (c) explain the difference between [[0] * 3] * 3 and [[0] * 3 for _ in range(3)] when one cell is set to 5.使用例题 7 的 grades 网格(3 名学生,3 次测试),(a) 求每名学生的平均分(保留一位小数),(b) 求每次测试的总分,(c) 解释把一个单元格设为 5 时 [[0] * 3] * 3 与 [[0] * 3 for _ in range(3)] 的区别。
# Pseudocode
FOR col FROM 0 TO 2:
SET t TO 0
FOR row FROM 0 TO 2:
SET t TO t + grades[row][col]
OUTPUT t
# Python
grades = [[85, 90, 78],
[72, 88, 94],
[91, 67, 83]]
for row in grades:
print(sum(row), round(sum(row) / len(row), 1))
# 253 84.3
# 254 84.7
# 241 80.3
col_totals = []
for col in range(3):
t = 0
for row in range(3):
t += grades[row][col]
col_totals.append(t)
print(col_totals, sum(col_totals)) # [248, 245, 255] 748
Row averages: 253 / 3 = 84.33, 254 / 3 = 84.67 and 241 / 3 = 80.33, which round to 84.3, 84.7 and 80.3. For column totals the loops swap roles: the outer loop fixes a column and the inner loop runs down the rows, reading grades[row][col]. The three column totals add up to 248 + 245 + 255 = 748, the same grand total as in Worked Example 7, which confirms the work.行平均值:253 / 3 = 84.33,254 / 3 = 84.67,241 / 3 = 80.33,分别四舍五入为 84.3、84.7 和 80.3。求列总和时两层循环的角色互换:外层循环固定一列,内层循环沿各行向下,读取 grades[row][col]。三个列总和相加为 248 + 245 + 255 = 748,与例题 7 的总和相同,说明计算正确。
wrong = [[0] * 3] * 3
wrong[0][1] = 5
print(wrong) # [[0, 5, 0], [0, 5, 0], [0, 5, 0]]
right = [[0] * 3 for _ in range(3)]
right[0][1] = 5
print(right) # [[0, 5, 0], [0, 0, 0], [0, 0, 0]]
The expression [0] * 3 builds one row, and the outer * 3 repeats that same row object three times, so wrong[0] is wrong[1] is True: changing one cell changes the cell in every row. The list comprehension runs [0] * 3 afresh on each pass, so each row is its own list and only row 0 changes.表达式 [0] * 3 创建一行,外层的 * 3 把同一个行对象重复三次,所以 wrong[0] is wrong[1] 为 True:改变一个单元格,每一行对应的单元格都会变。列表推导式每次迭代都重新执行 [0] * 3,因此每行都是独立的列表,只有第 0 行发生变化。
matrix = [[1,2,3],[4,5,6],[7,8,9]], what is matrix[2][0]?给定 matrix = [[1,2,3],[4,5,6],[7,8,9]],matrix[2][0] 是什么?matrix[2] is the third row: [7,8,9]. matrix[2][0] is the first element of that row: 7. Row index 2, column index 0.matrix[2] 是第三行:[7,8,9]。matrix[2][0] 是该行的第一个元素:7。行索引 2,列索引 0。Going deeper: real-world 2D array applications深入:二维数组的实际应用
Ontario ICS4U A3.5 specifically cites: "multiply each element by a constant, interchange elements, multiply matrices, process pixels in an image." Each is a nested-loop algorithm. Image processing is the most concrete: a greyscale image is a 2D array of integers 0-255; every filter (blur, sharpen, edge-detect) traverses this array with nested loops, computing a new value for each pixel from its neighbours. AB CSE2120 outcome 1.2.1 names "parallel arrays (look-up or associative tables)": these are 1D arrays used together as a primitive key-value store, a predecessor to the dictionary structure in §5.安大略 ICS4U A3.5 具体引用:"将每个元素乘以常数、交换元素、矩阵相乘、处理图像像素。"每个都是嵌套循环算法。图像处理最为具体:灰度图像是一个 0-255 整数的二维数组;每个滤镜(模糊、锐化、边缘检测)都使用嵌套循环遍历该数组,从其邻居计算每个像素的新值。AB CSE2120 结果 1.2.1 命名"并行数组(查找或关联表)",这些是共同用作原始键值存储的一维数组,是 §5 中字典结构的前身。
State the dimensions first: len(grid) is the number of rows and len(grid[0]) is the number of columns. Index with the row first and the column second, and write the first row and first column of the grid next to your working to check. For a row total the inner loop runs along the columns; for a column total the loops swap roles. Common errors: writing grid[col][row], summing across the wrong dimension, and building a grid with [[0] * n] * m, which repeats one row.
State 先写出尺寸:len(grid) 是行数,len(grid[0]) 是列数。索引时先行后列,并把网格的第一行和第一列写在草稿旁边用来核对。求行总和时内层循环沿列方向运行;求列总和时两层循环互换角色。常见错误:写成 grid[col][row];沿错误的维度求和;用 [[0] * n] * m 创建网格,这会重复同一行。
For grid = [[1, 2, 3, 4], [5, 6, 7, 8]], state the number of rows, the number of columns and the value of grid[1][2].对于 grid = [[1, 2, 3, 4], [5, 6, 7, 8]],写出行数、列数以及 grid[1][2] 的值。
len(grid) is 2 rows and len(grid[0]) is 4 columns. grid[1] is the second row [5, 6, 7, 8], and its index 2 is 7, so grid[1][2] is 7.
len(grid) 为 2 行,len(grid[0]) 为 4 列。grid[1] 是第二行 [5, 6, 7, 8],其索引 2 的值是 7,所以 grid[1][2] 是 7。
Write code that prints the largest value in each row of the same grid, and give the output.编写代码,输出同一个 grid 中每一行的最大值,并给出输出。
for row in grid: then m = row[0], an inner loop for v in row: with if v > m: m = v, and print(m) after it. It prints 4 and then 8 (the built-in max(row) gives the same).
for row in grid:,然后 m = row[0],内层循环 for v in row: 中写 if v > m: m = v,之后 print(m)。输出 4,然后是 8(内置的 max(row) 结果相同)。
Trace board = [[0] * 2] * 2, then board[1][0] = 7, then print(board). Explain the output.追踪 board = [[0] * 2] * 2,然后 board[1][0] = 7,然后 print(board)。解释输出结果。
It prints [[7, 0], [7, 0]]. Both rows are the same list object, so setting row 1 column 0 also sets row 0 column 0. Build the grid with [[0] * 2 for _ in range(2)] to get independent rows.
输出 [[7, 0], [7, 0]]。两行是同一个列表对象,所以设置第 1 行第 0 列的同时也改变了第 0 行第 0 列。用 [[0] * 2 for _ in range(2)] 创建网格才能得到相互独立的行。
Calculate the sum of the main diagonal of [[2, 0, 1], [4, 5, 6], [7, 8, 9]] using one loop.用一个循环计算 [[2, 0, 1], [4, 5, 6], [7, 8, 9]] 的主对角线之和。
The diagonal cells are grid[i][i] for i = 0, 1, 2, which are 2, 5 and 9. The sum is 2 + 5 + 9 = 16.
对角线上的单元格是 i = 0、1、2 时的 grid[i][i],即 2、5 和 9。和为 2 + 5 + 9 = 16。
Dictionaries and Maps (Key-Value Pairs) Honors字典与映射(键值对) Honors
- Create a dictionary, look up a value by key, add or update a pair, and iterate with
.items(). - Build a frequency table by counting with an
if/elseand with.get(key, default). - Explain when a lookup raises a
KeyErrorand two ways to avoid it. - State which values can be dictionary keys and which cannot, and name the error for a list key.
- Explain why adding keys while looping over a dictionary fails.
- 创建字典,按键查找值,添加或更新键值对,并用
.items()遍历。 - 用
if/else和.get(key, default)两种方式计数,建立频率表。 - 解释什么时候查找会引发
KeyError,以及两种避免方法。 - 说明哪些值可以做字典的键、哪些不可以,并写出列表做键时的错误名称。
- 解释为什么在遍历字典的同时添加键会失败。
- Key键: a unique label that identifies a value. Usually a string.:标识值的唯一标签,通常是字符串。
- Value值: any data associated with a key (int, string, list, etc.).:与键关联的任意数据(整数、字符串、列表等)。
- No integer index无整数索引: access by key:
d["name"]. Ontario ICS4U C1.1 names "dictionary" as an abstract data type.:通过键访问:d["name"]。安大略 ICS4U C1.1 将"字典"列为抽象数据类型。
dict. AB CSE2120 outcome 1.2.1 mentions "parallel arrays (look-up or associative tables)": dictionaries are the modern equivalent. AP CSA uses HashMap for this role.Python 使用 dict。AB CSE2120 结果 1.2.1 提到"并行数组(查找或关联表)",字典是现代等价物。AP CSA 使用 HashMap。
Worked Example 9: Student grade dictionary例题 9:学生成绩字典
Map student names (keys) to their average grade (values).将学生姓名(键)映射到其平均成绩(值)。
# Pseudocode
DECLARE grades AS DICTIONARY
SET grades["Alice"] TO 91
SET grades["Bob"] TO 78
OUTPUT grades["Bob"] # 78
SET grades["Dave"] TO 88
FOR EACH name, score IN grades:
OUTPUT name, score
# Python
grades = {}
grades["Alice"] = 91
grades["Bob"] = 78
print(grades["Bob"]) # 78
grades["Dave"] = 88
for name, score in grades.items():
print(name, score)
说明:dict["key"] 查找键值;dict.items() 返回所有键值对;赋值既可新增也可更新。Lookup by key is O(1) on average, much faster than linear search through a list for the same item.
Worked Example 10: Counting words with a dictionary例题 10:用字典统计单词
Count how often each word occurs in words = ["red", "blue", "red", "green", "blue", "red"], show two ways to avoid a KeyError, and find the most frequent word.统计 words = ["red", "blue", "red", "green", "blue", "red"] 中每个单词出现的次数,给出两种避免 KeyError 的方法,并找出出现次数最多的单词。
# Pseudocode
SET counts TO empty dictionary
FOR EACH w IN words:
IF w IS A KEY OF counts THEN
SET counts[w] TO counts[w] + 1
ELSE
SET counts[w] TO 1
# Python
words = ["red", "blue", "red", "green", "blue", "red"]
counts = {}
for w in words:
if w in counts:
counts[w] += 1
else:
counts[w] = 1
print(counts) # {'red': 3, 'blue': 2, 'green': 1}
# the same count with .get (default 0 for a missing key)
counts2 = {}
for w in words:
counts2[w] = counts2.get(w, 0) + 1
print(counts2 == counts) # True
print(counts.get("yellow")) # None
print(counts.get("yellow", 0)) # 0
# print(counts["yellow"]) # KeyError: 'yellow'
best = None
for word, n in counts.items():
if best is None or n > counts[best]:
best = word
print(best, counts[best]) # red 3
The first time a word appears it is not yet a key, so counts[w] += 1 alone would raise a KeyError. The if w in counts test handles the first sighting, and .get(w, 0) does the same by supplying 0 for a missing key. Keys are unique: assigning to an existing key updates its value, so red goes 1, 2, 3. The counts add up to 3 + 2 + 1 = 6, the number of words in the list, which is a good check.一个单词第一次出现时还不是键,所以单独写 counts[w] += 1 会引发 KeyError。if w in counts 测试处理第一次出现的情况,.get(w, 0) 则为缺失的键提供 0,效果相同。键是唯一的:给已有的键赋值就是更新它的值,所以 red 依次为 1、2、3。各计数之和为 3 + 2 + 1 = 6,等于列表中的单词数,这是一个很好的核对方法。
To find the most frequent word, loop over .items() and keep the word with the largest count so far. Python 3.7 and later keeps the insertion order, so the items come out as red, blue, green.要找出现最多的单词,遍历 .items(),保留目前计数最大的单词。Python 3.7 及以后会保持插入顺序,所以条目按 red、blue、green 的顺序出现。
d = {"x": 10, "y": 20, "z": 30}, what is d["y"]?给定 d = {"x": 10, "y": 20, "z": 30},d["y"] 是什么?d["y"] returns the value associated with key "y": 20. The key is "y"; the value is 20.d["y"] 返回键 "y" 对应的值:20。键是 "y";值是 20。d["y"] returns 20.字典查找返回值,不是键。d["y"] 返回 20。Justify a dictionary with its access pattern: lookup by key, one value per unique key. State the output of a lookup only after checking that the key exists, because a missing key raises a KeyError while .get returns None or the default you give. Use curly brackets to create a dictionary and square brackets to look up a key. Common errors: confusing the key with the value, expecting a duplicate key to create a second entry (it overwrites the first), and using a list as a key.
Justify 使用字典时,用它的访问方式作理由:按键查找,每个唯一的键对应一个值。State 查找结果之前先确认键存在,因为缺失的键会引发 KeyError,而 .get 返回 None 或你给定的默认值。创建字典用花括号,查找键用方括号。常见错误:混淆键和值;以为重复的键会产生第二个条目(其实会覆盖第一个);用列表做键。
Trace d = {"x": 10, "y": 20}, then d["z"] = 30, then d["x"] = 11. State d and len(d).追踪 d = {"x": 10, "y": 20},然后 d["z"] = 30,然后 d["x"] = 11。写出 d 和 len(d)。
d["z"] = 30 adds a new pair and d["x"] = 11 updates an existing one. So d is {'x': 11, 'y': 20, 'z': 30} and len(d) is 3.
d["z"] = 30 添加新键值对,d["x"] = 11 更新已有的键值对。所以 d 是 {'x': 11, 'y': 20, 'z': 30},len(d) 是 3。
Explain why d["w"] raises an error for the dictionary above and give two ways to avoid it.解释为什么对上面的字典执行 d["w"] 会报错,并给出两种避免方法。
The key "w" is not in the dictionary, so Python raises a KeyError. Test first with if "w" in d:, or use d.get("w", 0), which returns the default 0 instead of an error.
键 "w" 不在字典中,所以 Python 引发 KeyError。可以先用 if "w" in d: 测试,或使用 d.get("w", 0),它返回默认值 0 而不是报错。
Why does d[[1, 2]] = "A1" fail, and what can be used instead?为什么 d[[1, 2]] = "A1" 会失败?可以用什么代替?
A list is mutable, so it cannot be a key: Python raises a TypeError (unhashable type). A tuple is immutable, so d[(1, 2)] = "A1" works.
列表是可变的,不能做键:Python 引发 TypeError(unhashable type)。元组不可变,所以 d[(1, 2)] = "A1" 可以正常工作。
The loop for k in d: d[k + "w"] = 0 stops with an error. Why, and how can the loop be written safely?循环 for k in d: d[k + "w"] = 0 会因报错而停止。原因是什么?如何安全地改写?
The loop adds keys to the dictionary while it is being iterated, so Python raises a RuntimeError (dictionary changed size during iteration). Loop over a copy of the keys instead: for k in list(d):.
该循环在遍历字典的同时向字典添加键,所以 Python 引发 RuntimeError(dictionary changed size during iteration)。应改为遍历键的副本:for k in list(d):。
Tuples and Sets元组与集合
- State the defining properties of a tuple (ordered, immutable) and of a set (unordered, unique elements).
- Show that a tuple cannot be changed, use tuple unpacking, and write a one-item tuple correctly.
- Use
set()to remove duplicates and to count distinct values. - Evaluate union, intersection, difference and symmetric difference of two small sets.
- Use a tuple as a dictionary key, and create an empty set correctly.
- 说出元组(有序、不可变)和集合(无序、元素唯一)的定义性质。
- 说明元组不能被修改,使用元组解包(
unpacking),并正确写出只含一个元素的元组。 - 用
set()去除重复项并统计不同值的个数。 - 计算两个小集合的并集、交集、差集和对称差集。
- 把元组用作字典的键,并正确创建空集合。
- Tuple元组: ordered, immutable sequence. Once created, elements cannot be changed. Use for fixed data: coordinates
(lat, lon), RGB colours(255, 128, 0). Python syntax: round brackets(x, y).:有序、不可变序列。创建后不能更改元素。用于固定数据:坐标(lat, lon)、RGB 颜色(255, 128, 0)。Python 语法:圆括号(x, y)。 - Set集合: unordered collection of unique elements. Automatically removes duplicates. Fast membership testing and set operations (union, intersection, difference). Python syntax:
{x, y}orset().:无序的唯一元素集合。自动删除重复项。快速成员测试和集合运算(并集、交集、差集)。Python 语法:{x, y}或set()。
Worked Example 11: Tuples and sets in practice例题 11:元组与集合实战
Practical uses of both types with Python code.两种类型的实际使用,附 Python 代码。
# Tuple: immutable record
point = (3, 7)
print(point[0]) # 3
# point[0] = 5 # ERROR: tuples are immutable!
a, b = 10, 20
a, b = b, a # swap using tuple unpacking
print(a, b) # 20 10
元组用于固定搭配的数据;不可变性防止意外修改。Tuples are ideal for return values and dictionary keys because they cannot be accidentally modified.
# Set: unique elements only
scores = [85, 90, 85, 74, 90, 65]
unique = set(scores)
print(unique) # the four values 65, 74, 85, 90 (display order may differ)
print(85 in unique) # True
print(100 in unique) # False
classA = {"Alice", "Bob", "Carol"}
classB = {"Bob", "Dave", "Carol"}
print(classA & classB) # Bob and Carol (display order may differ)
print(classA | classB) # all four names
print(classA - classB) # Alice
集合自动去重;& 交集,| 并集,- 差集。成员测试 in 对集合平均 O(1),对列表 O(n)。Use a set when you need fast membership testing, deduplication, or set-algebra on two groups.
Worked Example 12: Comparing two sign-up lists with sets例题 12:用集合比较两份报名名单
The chess club list is chess = ["Ana", "Ben", "Chen", "Dia", "Ben"] and the robotics list is robotics = ["Chen", "Eli", "Ana", "Fay"]. Find (a) how many distinct students signed up for chess, (b) who is in both clubs, (c) who is in either club, (d) who is in chess only. Then store seat names under tuple keys.国际象棋社名单是 chess = ["Ana", "Ben", "Chen", "Dia", "Ben"],机器人社名单是 robotics = ["Chen", "Eli", "Ana", "Fay"]。求 (a) 有多少名不同的学生报名了国际象棋,(b) 谁同时在两个社团,(c) 谁在任一社团,(d) 谁只在国际象棋社。然后用元组做键存放座位姓名。
# Python
chess = ["Ana", "Ben", "Chen", "Dia", "Ben"]
robotics = ["Chen", "Eli", "Ana", "Fay"]
cs = set(chess)
rs = set(robotics)
print(len(chess), len(cs)) # 5 4
print(sorted(cs & rs)) # ['Ana', 'Chen']
print(sorted(cs | rs)) # ['Ana', 'Ben', 'Chen', 'Dia', 'Eli', 'Fay']
print(sorted(cs - rs)) # ['Ben', 'Dia']
print(sorted(cs ^ rs)) # ['Ben', 'Dia', 'Eli', 'Fay']
seats = {(0, 1): "Ana", (0, 2): "Ben"}
print(seats[(0, 1)]) # Ana
single = (5,)
print(type(single).__name__, type((5)).__name__) # tuple int
(a) The chess list has 5 entries but Ben appears twice, so the set has 4 distinct students. (b) The intersection & holds the students in both clubs: Ana and Chen. (c) The union | holds everyone in either club: 6 students, which matches 4 + 4 - 2, because the 2 students in both were counted twice. (d) The difference - holds the students in chess only: Ben and Dia. The symmetric difference ^ holds those in exactly one club: Ben, Dia, Eli and Fay.(a) 国际象棋名单有 5 条记录,但 Ben 出现了两次,所以集合中有 4 名不同的学生。(b) 交集 & 是两个社团都有的学生:Ana 和 Chen。(c) 并集 | 是任一社团中的所有学生:共 6 名,与 4 + 4 - 2 相符,因为同时在两个社团的 2 名学生被算了两次。(d) 差集 - 是只在国际象棋社的学生:Ben 和 Dia。对称差集 ^ 是恰好只在一个社团的学生:Ben、Dia、Eli 和 Fay。
A set has no order, so the examples use sorted() to print a predictable list. The tuple (0, 1) is immutable, so it can be a dictionary key for a seat position. A single-item tuple needs the comma: (5,) is a tuple, while (5) is just the integer 5 in brackets.集合没有顺序,所以示例用 sorted() 输出可预测的列表。元组 (0, 1) 不可变,因此可以做表示座位位置的字典键。只含一个元素的元组必须带逗号:(5,) 是元组,而 (5) 只是括号里的整数 5。
in is O(1) on average vs O(n) for a list; sets automatically prevent duplicates; no ordering needed.集合最理想:in 平均 O(1),而列表 O(n);自动防止重复;不需要排序。State the defining property first: a tuple is immutable, a set holds unique elements with no order. Compare a tuple and a list by mutability, not by speed. Do not rely on the printed order of a set; if you must show it, use sorted(). Common errors: writing {} for an empty set (it makes an empty dictionary, so use set()), writing (5) for a one-item tuple, and expecting a set to keep duplicates or an index such as s[0].
State 先写出定义性质:元组不可变,集合元素唯一且无序。Compare 元组与列表时,比较可变性,而不是速度。不要依赖集合的输出顺序;如需展示,使用 sorted()。常见错误:用 {} 表示空集合(它创建的是空字典,应使用 set());用 (5) 表示只含一个元素的元组;以为集合会保留重复项,或可以用 s[0] 这样的索引。
What happens with t = (4, 8) followed by t[0] = 1? Which structure should store a map point that must not change?t = (4, 8) 之后执行 t[0] = 1 会发生什么?存放不能改变的地图坐标点应使用哪种结构?
A tuple is immutable, so Python raises a TypeError (a tuple does not support item assignment). A fixed point such as (4, 8) belongs in a tuple, which protects it from accidental change.
元组不可变,所以 Python 引发 TypeError(元组不支持元素赋值)。像 (4, 8) 这样的固定坐标点应放在元组里,这样可以避免被意外修改。
How many distinct values does set([4, 4, 7, 9, 7]) contain, and which values are they?set([4, 4, 7, 9, 7]) 含有多少个不同的值?它们是哪些?
Duplicates are removed, leaving the values 4, 7 and 9 (in any display order), so len(set([4, 4, 7, 9, 7])) is 3.
重复项被去除,留下 4、7 和 9(显示顺序不限),所以 len(set([4, 4, 7, 9, 7])) 是 3。
For A = {1, 2, 3, 4} and B = {3, 4, 5}, find A | B, A & B, A - B and B - A.对于 A = {1, 2, 3, 4} 和 B = {3, 4, 5},求 A | B、A & B、A - B 和 B - A。
Union: 1, 2, 3, 4, 5. Intersection: 3 and 4. A - B: 1 and 2. B - A: 5 (so the difference depends on the order of the operands).
并集:1、2、3、4、5。交集:3 和 4。A - B:1 和 2。B - A:5(所以差集取决于操作数的顺序)。
What does type({}) give, and how do you create an empty set?type({}) 的结果是什么?如何创建空集合?
It gives dict: empty curly brackets make an empty dictionary. Create an empty set with set().
结果是 dict:空花括号创建的是空字典。创建空集合要用 set()。
Choosing the Right Data Structure选择合适的数据结构
- Choose a list, 2D list, dictionary, set or tuple for a described problem, and justify the choice.
- Justify a choice using four properties: ordered, mutable, duplicates allowed, and how items are accessed.
- Combine structures, such as a dictionary whose values are lists, and write the loop that builds it.
- Identify the key operation in a requirement (lookup by position, lookup by key, or membership) and match it to a structure.
- 为所描述的问题选择列表、二维列表、字典、集合或元组,并说明理由。
- 用四个性质说明选择:是否有序、是否可变、是否允许重复、如何访问元素。
- 组合使用多种结构,例如值为列表的字典,并编写构建它的循环。
- 找出需求中的关键操作(按位置查找、按键查找或成员测试),并与合适的结构匹配。
- List / 1D array列表 / 一维数组: ordered sequence accessed by position. Default choice.:有序序列,通过位置访问。默认选择。
- 2D array二维数组: grid-shaped data: game boards, images, matrices.:网格形状的数据:游戏棋盘、图像、矩阵。
- Dictionary字典: fast lookup by label/ID. Use when you have key-value data.:按标签/ID 快速查找。有键值数据时使用。
- Set集合: uniqueness and fast membership testing.:唯一性和快速成员测试。
- Tuple元组: fixed, immutable grouping of related values.:相关值的固定、不可变组合。
| Structure结构 | Ordered?有序? | Mutable?可变? | Duplicates?允许重复? | Best for最适合 |
|---|---|---|---|---|
| List列表 | Yes是 | Yes是 | Yes是 | Sequences, ordered data序列、有序数据 |
| 2D array二维数组 | Yes是 | Yes是 | Yes是 | Grids, tables, images网格、表格、图像 |
| Dictionary字典 | Yes (Py 3.7+)是(Py 3.7+) | Yes是 | Keys: No键:否 | Labelled data, fast lookup带标签数据、快速查找 |
| Set集合 | No否 | Yes是 | No否 | Unique items, set ops唯一项目、集合运算 |
| Tuple元组 | Yes是 | No否 | Yes是 | Fixed records, return values固定记录、返回值 |
Worked Example 13: Justify a structure for four requirements例题 13:为四项需求选择并论证数据结构
A library program must (a) check quickly whether a book ID is currently on loan, (b) look up a title from a book ID, (c) store the (shelf, position) location of a book, which never changes, and (d) keep the order in which people joined a waiting list, removing names from the front. Choose a structure for each and justify it.图书馆程序需要 (a) 快速检查某个图书编号当前是否已借出,(b) 通过图书编号查找书名,(c) 存储图书的(书架,位置),它永远不变,(d) 保持人们加入等候名单的顺序,并从队首移除名字。为每项选择一种结构并说明理由。
# Python
on_loan = {1042, 2210, 3055} # (a) set: fast membership test
print(1042 in on_loan, 1043 in on_loan) # True False
titles = {1042: "Dune", 2210: "Emma"} # (b) dict: book ID -> title
print(titles[2210]) # Emma
location = (3, 14) # (c) tuple: fixed (shelf, position)
queue = ["Ana", "Ben", "Chen"] # (d) list: ordered, remove from the front
print(queue.pop(0), queue) # Ana ['Ben', 'Chen']
Match the operation each requirement needs to a structure. (a) The only question is whether an ID is in a group, with no order and no repeats: a set, whose membership test is O(1) on average, where a list needs O(n). (b) Each unique ID has one title: a dictionary, looked up by key. (c) A location that must never change: a tuple, which is immutable. (d) The order of arrival matters, names leave from the front and the same name can be added again: a list.把每个需求所需的操作与结构匹配。(a) 唯一的问题是某个编号是否在一组中,不要求顺序也没有重复:用集合,其成员测试平均为 O(1),而列表需要 O(n)。(b) 每个唯一编号对应一个书名:用字典,按键查找。(c) 一个绝不能改变的位置:用元组,它不可变。(d) 到达顺序很重要,名字从队首离开,同一个名字也可能再次加入:用列表。
The justification names the property, not just the structure: ordered, mutable, duplicates, and how the items are accessed. A common error is to choose a list for everything, because a list is the structure you meet first. Removing the front of a long list with pop(0) shifts every later element, which is fine here but slow for very large queues.说明理由时要写出性质,而不是只写结构名称:是否有序、是否可变、是否允许重复,以及如何访问元素。常见错误是什么都用列表,因为列表是最先接触的结构。对很长的列表用 pop(0) 删除队首会移动后面的每个元素,这里没有问题,但对非常大的队列会很慢。
Worked Example 14: Group names by letter grade (a dictionary of lists)例题 14:按字母成绩给姓名分组(值为列表的字典)
Given the records students = [("Ana", "A"), ("Ben", "B"), ("Chen", "A"), ("Dia", "C")], build a dictionary that maps each letter grade to the list of students who earned it, then read off the number of students with grade A and the second one.给定记录 students = [("Ana", "A"), ("Ben", "B"), ("Chen", "A"), ("Dia", "C")],构建一个把每个字母成绩映射到取得该成绩的学生列表的字典,然后读出成绩为 A 的学生人数以及其中的第二名。
# Pseudocode
SET groups TO empty dictionary
FOR EACH (name, letter) IN students:
IF letter IS NOT A KEY OF groups THEN
SET groups[letter] TO empty list
APPEND name TO groups[letter]
# Python
students = [("Ana", "A"), ("Ben", "B"), ("Chen", "A"), ("Dia", "C")]
groups = {}
for name, letter in students:
groups.setdefault(letter, []).append(name)
print(groups) # {'A': ['Ana', 'Chen'], 'B': ['Ben'], 'C': ['Dia']}
print(len(groups["A"])) # 2
print(groups["A"][1]) # Chen
Each record is a tuple (a fixed pair), the records sit in a list (an ordered collection that can hold many), and the result is a dictionary from each letter to a list of names. The call groups.setdefault(letter, []) returns the list stored under letter, first inserting an empty list when the key is missing, so .append(name) always has a list to add to. The pseudocode shows the same idea with an explicit test.每条记录是一个元组(固定的一对),记录放在列表中(可容纳许多条的有序集合),结果是一个从每个字母映射到姓名列表的字典。调用 groups.setdefault(letter, []) 会返回存放在 letter 下的列表,键缺失时先插入一个空列表,所以 .append(name) 总有列表可添加。伪代码用显式测试表达了同样的想法。
Reading the result: groups["A"] is ['Ana', 'Chen'], so its length is 2 and groups["A"][1] is 'Chen'. Two index steps are used: a key to pick the list, then a position to pick the name.读取结果:groups["A"] 是 ['Ana', 'Chen'],所以它的长度是 2,groups["A"][1] 是 'Chen'。这里用了两步索引:先用键选出列表,再用位置选出姓名。
word_counts["hello"] += 1 is the canonical pattern.将标签与值关联并频繁更新,选字典。word_counts["hello"] += 1 是典型模式。board[row][col] maps directly to the physical layout and gives O(1) access.棋盘是经典的 8×8 网格。二维数组 board[row][col] 直接映射物理布局,提供 O(1) 访问。Justify and compare questions want the structure and the property that decides it. Write a sentence such as: a dictionary, because each ID is looked up by key; a set, because only membership matters and duplicates are not wanted. Check the four properties in turn (ordered, mutable, duplicates, access). Common errors: choosing a list when the question is about lookup by name, choosing a tuple for data that must change, and choosing a dictionary when only a yes/no membership test is needed.
Justify 和 compare 类题目要求写出结构以及起决定作用的性质。可以这样写:用字典,因为按键查找每个编号;用集合,因为只关心成员关系且不需要重复项。依次检查四个性质(有序、可变、重复、访问方式)。常见错误:题目是按名字查找却选了列表;对需要修改的数据选了元组;只需要是/否的成员测试却选了字典。
A program stores the red, green and blue values of one pixel, (255, 128, 0), which never change. Which structure fits, and why?程序存储一个像素的红、绿、蓝值 (255, 128, 0),这些值永远不变。哪种结构合适?为什么?
A tuple: it is ordered (red, green, blue in a fixed position), immutable (the colour cannot be changed by accident) and holds a small fixed record.
元组:它有序(红、绿、蓝位置固定)、不可变(颜色不会被意外修改),并且保存一条小而固定的记录。
A site must repeatedly check whether one of 10 000 student IDs is registered. Which structure is best, and why?网站需要反复检查 10 000 个学生编号中的某一个是否已注册。哪种结构最好?为什么?
A set. Only membership matters, IDs are unique and order is not needed, and the test id in registered is O(1) on average, while a list would need O(n) comparisons for each check.
集合。只关心成员关系,编号唯一,不需要顺序,而且 id in registered 测试平均为 O(1),而列表每次检查需要 O(n) 次比较。
A 3 by 3 game board stores X, O or a space in each square. Which structure fits, and how is the centre square read?一个 3 乘 3 的游戏棋盘每个方格存放 X、O 或空格。哪种结构合适?如何读取中心方格?
A 2D list, because the data has rows and columns. With rows and columns numbered from 0, the centre square is board[1][1].
二维列表,因为数据有行和列。行和列都从 0 开始编号时,中心方格是 board[1][1]。
Given inventory = {"apple": 4, "pear": 0}, write the statements that add 5 pears and a new item "fig" with 2, then calculate the total number of items.给定 inventory = {"apple": 4, "pear": 0},写出增加 5 个 pear 并新增 2 个 "fig" 的语句,然后计算物品总数。
inventory["pear"] += 5 updates the pear count to 5, and inventory["fig"] = 2 adds a new pair. The total is sum(inventory.values()) = 4 + 5 + 2 = 11.
inventory["pear"] += 5 把 pear 的数量更新为 5,inventory["fig"] = 2 添加一个新键值对。总数是 sum(inventory.values()) = 4 + 5 + 2 = 11。
Exam Strategy and Common Pitfalls考试策略与常见陷阱
- State why, not just what.说明原因,不只是说明是什么。 When asked to choose a data structure on an exam, always justify: "I use a dictionary because lookup by student name is O(1)." Naming the structure without a justification is an incomplete answer.在考试中被要求选择数据结构时,始终给出理由:"我使用字典,因为按学生姓名查找是 O(1)。"仅命名结构而不说明原因,答案并不完整。
- Know the four distinguishing traits.了解四个区分特征。 For any structure: is it ordered? is it mutable? does it allow duplicates? how is it accessed (index, key, or membership)? Knowing these for all five structures in this guide is the CSTA 3B-AP-12 competency.对于任何结构:是有序的吗?是可变的吗?允许重复吗?如何访问(索引、键或成员关系)?了解本指南中所有五种结构的这些特征是 CSTA 3B-AP-12 能力要求。
- Zero-based vs one-based.从零开始 vs 从一开始。 Python/Java are 0-indexed; AP CSP pseudocode is 1-indexed. Off-by-one is the most common indexing error. Always check: first element is
list[0]in Python,list[1]in AP CSP pseudocode.Python/Java 从零开始;AP CSP 伪代码从一开始。差一是最常见的索引错误。始终检查:Python 中第一个元素是list[0],AP CSP 伪代码中是list[1]。 - Out-of-bounds is a runtime error.越界是运行时错误。 Accessing index 5 in a list of length 5 raises an IndexError (Python) or ArrayIndexOutOfBoundsException (Java). State this explicitly when asked about error types in array code.在长度为 5 的列表中访问索引 5 会引发 IndexError(Python)或 ArrayIndexOutOfBoundsException(Java)。在被问及数组代码中的错误类型时明确说明这一点。
- Row first, column second.先行,后列。 2D access is always
grid[row][col]. Reversing the order accesses the wrong element. Confirm by writing out the first row and first column explicitly in your working.二维访问始终是grid[row][col]。颠倒顺序会访问错误元素。在草稿中明确写出第一行和第一列来确认。 - Tuples as dict keys.元组作为字典键。 In Python, tuples (immutable) can be dictionary keys; lists (mutable) cannot. This is a common gotcha:
d[(1,2)] = "A1"works;d[[1,2]] = "A1"raises TypeError.在 Python 中,元组(不可变)可以是字典键;列表(可变)不能。这是常见的陷阱:d[(1,2)] = "A1"有效;d[[1,2]] = "A1"引发 TypeError。
- Trace before you submit.提交前先追踪。 For any code-reading or pseudocode question, hand-trace with a concrete example to verify. A trace table takes 60 seconds and catches index and logic errors.对于任何代码阅读或伪代码问题,用具体示例手工追踪验证。追踪表只需 60 秒,能发现索引和逻辑错误。
- Use correct Python method names.使用正确的 Python 方法名称。
append()notadd();remove(value)notdelete(value);pop(index)to remove by position. Use the exact method names, because Python will not recognise a near miss.append()不是add();remove(value)不是delete(value);pop(index)按位置删除。请使用准确的方法名,因为 Python 不会识别近似的名称。
Flashcards闪卡
append(x) adds x to the end. insert(i, x) adds x before index i, shifting later elements right. AP CSP AAP-2.K requires knowing both.append(x) 在末尾添加 x。insert(i, x) 在索引 i 前添加 x,后面元素右移。AP CSP AAP-2.K 要求掌握两者。remove(value) deletes first occurrence of value. pop(index) removes by position and returns the element.remove(value) 删除第一次出现的值。pop(index) 按位置删除并返回该元素。grid[row][col]. Row index first, column index second. Traverse with nested loops: outer for rows, inner for columns.grid[row][col]。先行索引,后列索引。用嵌套循环遍历:外层遍历行,内层遍历列。d["key"] = value to set; d["key"] to get; d.items() to iterate. O(1) average lookup.唯一键到值的映射。d["key"] = value 设置;d["key"] 获取;d.items() 迭代。平均 O(1) 查找。(x, y).不可变的有序序列。创建后不能更改。用于固定记录、坐标、字典键。Python:(x, y)。x in s is O(1). Set ops: & intersection, | union, - difference.无序,唯一元素。无重复。快速成员测试:x in s 是 O(1)。集合运算:& 交集,| 并集,- 差集。counts["hello"] += 1. O(1) per update.字典(单词→计数)。键是单词(字符串),值是计数(整数)。counts["hello"] += 1。每次更新 O(1)。board[row][col]. Natural row-column grid. O(1) access. Traverse all squares with nested loops.二维数组 board[row][col]。自然的行列网格。O(1) 访问。用嵌套循环遍历所有方格。Practice Quiz综合测验
items = ["pen", "book", "ruler", "eraser"], what is len(items)?给定 items = ["pen", "book", "ruler", "eraser"],len(items) 是什么?len() returns the number of elements. The list has 4 elements. Last valid index = 4 − 1 = 3.len() 返回元素数量。列表有 4 个元素。最后有效索引 = 4 − 1 = 3。len() counts elements, not the last index.数元素:"pen"、"book"、"ruler"、"eraser" = 4 个元素。len() 计算元素数量,不是最后一个索引。nums = [10, 20, 30] then nums.append(40), what is nums?执行 nums = [10, 20, 30] 然后 nums.append(40) 后,nums 是什么?append(40) adds 40 to the end of the list. Result: [10, 20, 30, 40].append(40) 在列表末尾添加 40。结果:[10, 20, 30, 40]。append() always adds to the end. Use insert(0, x) to add at the beginning.append() 始终在末尾添加。使用 insert(0, x) 在开头添加。grid = [[1,2],[3,4],[5,6]], what is grid[1][0]?给定 grid = [[1,2],[3,4],[5,6]],grid[1][0] 是什么?grid[1] = [3, 4] (second row). grid[1][0] = 3 (first element of that row).grid[1] = [3, 4](第二行)。grid[1][0] = 3(该行第一个元素)。[5, 2, 5, 8, 2, 3] and you want to know how many distinct values it contains. What is the simplest Python approach?你有列表 [5, 2, 5, 8, 2, 3],想知道它包含多少个不同的值。最简单的 Python 方法是什么?set() removes duplicates, leaving the values 2, 3, 5 and 8 (Python may display them in a different order). len() counts: 4 distinct values. This is the idiomatic Python one-liner for counting unique elements.set() 去重,留下 2、3、5、8 这几个值(Python 显示顺序可能不同)。len() 计数:4 个不同值。这是计算唯一元素的惯用 Python 单行代码。len(set(lst)) counts distinct values in one step: the simplest approach.转换为集合会自动去重。len(set(lst)) 一步计算不同值,最简单的方法。Readiness Checklist准备就绪清单
Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。
- Declare, initialise, and access elements of a 1D array by index; state the last valid index for an array of given length; explain what out-of-bounds means. 🇨🇦 ON ICS3U A1.5-A1.6 / AB CSE2120 1.2.1声明、初始化并通过索引访问一维数组元素;说明给定长度数组的最后有效索引;解释越界的含义。🇨🇦 ON ICS3U A1.5-A1.6 / AB CSE2120 1.2.1
- Write traversal loops for three patterns: sum all elements, find the maximum value, and linear search (return index or −1). 🇺🇸 AP CSP AAP-2.K / 🇨🇦 ON ICS3U A2.3为三种模式编写遍历循环:求所有元素之和、找最大值、线性搜索(返回索引或 −1)。🇺🇸 AP CSP AAP-2.K / 🇨🇦 ON ICS3U A2.3
- Use
append(),insert(i, x),remove(value), andpop(index)correctly; predict the state of a list after a sequence of these operations. 🇺🇸 AP CSP AAP-2.K / 🇨🇦 AB CSE2120 1.3.2正确使用append()、insert(i, x)、remove(value)和pop(index);预测一系列操作后列表的状态。🇺🇸 AP CSP AAP-2.K / 🇨🇦 AB CSE2120 1.3.2 - Access any element of a 2D array using
grid[row][col]; write nested loops to traverse all elements; sum all values in a given 2D array. 🇨🇦 ON ICS4U A3.5使用grid[row][col]访问二维数组的任意元素;编写嵌套循环遍历所有元素;求给定二维数组中所有值的和。🇨🇦 ON ICS4U A3.5 - Create a Python dict, look up a value by key, add a new key-value pair, and iterate over all pairs using
.items(). Explain why dict lookup is faster than list search. 🇨🇦 ON ICS4U C1.1 / AB CSE2120 1.2.1创建 Python 字典,通过键查找值,添加新键值对,并用.items()遍历所有对。解释为何字典查找比列表搜索更快。🇨🇦 ON ICS4U C1.1 / AB CSE2120 1.2.1 - Explain what makes a tuple different from a list (immutability); create a set from a list to remove duplicates; use
into test membership in a set; perform union, intersection, and difference on two sets. 🇺🇸 CSTA 3B-AP-12 / 🇨🇦 BC CP12解释元组与列表的区别(不可变性);从列表创建集合以去重;用in测试集合的成员关系;对两个集合执行并集、交集和差集操作。🇺🇸 CSTA 3B-AP-12 / 🇨🇦 BC CP12 - For a given problem, justify which data structure (list, 2D array, dict, set, tuple) is the best fit and explain why, citing ordered/mutable/duplicate properties. 🇺🇸 CSTA 3B-AP-12对于给定问题,说明哪种数据结构(列表、二维数组、字典、集合、元组)最合适并解释原因,引用有序性/可变性/重复性属性。🇺🇸 CSTA 3B-AP-12
- State verbatim CSTA 3B-AP-12 ("Compare and contrast fundamental data structures and their uses") and its Descriptive Statement example list. 🇺🇸 CSTA Level 3B逐字陈述 CSTA 3B-AP-12("比较和对比基本数据结构及其用途")及其描述性声明示例列表。🇺🇸 CSTA Level 3B
- Explain the AP CSP pseudocode list notation (1-indexed, APPEND/INSERT/REMOVE/LENGTH) and correctly re-index a Python-indexed answer when translating to AP CSP pseudocode. 🇺🇸 AP CSP AAP-2.K Topic 3.10解释 AP CSP 伪代码列表表示法(从 1 开始索引,APPEND/INSERT/REMOVE/LENGTH),并在翻译为 AP CSP 伪代码时正确重新索引 Python 索引的答案。🇺🇸 AP CSP AAP-2.K 主题 3.10
- Name the Alberta CSE module for data structures (CSE2120) and state its level (Intermediate) and prerequisite (CSE2110). Cite at least one verbatim outcome. 🇨🇦 AB CSE2120说明阿尔伯塔数据结构的 CSE 模块(CSE2120)、其级别(中级)和先修要求(CSE2110)。引用至少一个逐字结果。🇨🇦 AB CSE2120
- Honors: ICS4U / CSE2120 Implement insert and delete at an arbitrary index in a 1D array using a loop (shift elements); write a nested-loop algorithm to find the sum of all elements in a 2D array. 🇨🇦 ON ICS4U A3.3 & A3.5 / AB CSE2120 1.3.2荣誉:ICS4U / CSE2120 使用循环(移动元素)在一维数组的任意索引处实现插入和删除;编写嵌套循环算法求二维数组所有元素之和。🇨🇦 ON ICS4U A3.3 & A3.5 / AB CSE2120 1.3.2
What This Feeds Into本单元的去向
Data structures are the bridge between introductory programming (variables, loops, functions) and higher-level course work in AP CSA and university CS. Every algorithm you will write at the AP level manipulates one or more of the structures covered in this guide. The feeder link below points to the AP CSA Data Collection guide (ArrayList, arrays) which builds directly on this unit.数据结构是初级编程(变量、循环、函数)与 AP CSA 和大学 CS 高阶课程之间的桥梁。你在 AP 层次编写的每个算法都操作本指南中涵盖的一种或多种结构。以下衔接链接指向 AP CSA 数据收集指南(ArrayList、数组),它直接建立在本单元基础上。
Within High School Computer Science.在 HS Computer Science 内部。
Unit 6 (Strings and Text Processing) treats strings as sequences and applies indexing and traversal patterns from this unit to text. Unit 7 (Searching and Sorting) builds directly on 1D array traversal (§2) and introduces formal algorithm efficiency (extending the choosing-the-right-structure thinking of §7). Unit 8 (OOP) uses lists and dicts extensively as object attributes. Mastering this unit is a prerequisite for all of them.第 6 单元(字符串和文本处理)将字符串视为序列,并将本单元的索引和遍历模式应用于文本。第 7 单元(搜索与排序)直接建立在一维数组遍历(§2)基础上,并引入正式的算法效率(扩展 §7 的选择正确结构的思维)。第 8 单元(OOP)广泛使用列表和字典作为对象属性。掌握本单元是所有这些单元的先决条件。
AP feeder links (existing in this repo).AP 衔接链接(本仓库中已有)。
AP CSP Big Idea 3 Topic 3.10 (lists, AAP-2.K) covers list operations: practise tracing them (APPEND, INSERT, REMOVE, LENGTH) on pseudocode and predicting the result. AP CSA (Java) expands every structure here: arrays become int[], lists become ArrayList<E>, dicts become HashMap<K,V>, and 2D arrays become int[][]. The conceptual foundation is identical; only the syntax changes. CSTA 3B-AP-12 (compare/contrast data structures) is the Level 3B standard that ties this guide to the AP-track pipeline.AP CSP 大概念 3 主题 3.10(列表,AAP-2.K)涵盖列表操作:请练习追踪伪代码中的列表操作(APPEND、INSERT、REMOVE、LENGTH)并预测结果。AP CSA(Java)扩展了这里的每种结构:数组变为 int[],列表变为 ArrayList<E>,字典变为 HashMap<K,V>,二维数组变为 int[][]。概念基础相同;只是语法不同。CSTA 3B-AP-12(比较/对比数据结构)是将本指南与 AP 轨道衔接的 3B 级标准。
This is the ladder we coach students up: from these high school foundations into AP and IB, and on to first-year university. If you would rather have a guide for the next step than take it on trust, Dingrui Scholars tutors teach exactly this path in one-on-one sessions and small-group classes. A free assessment is the place to start.这正是我们陪伴学生攀登的阶梯:从这些高中基础,迈入 AP 与 IB,再走向大学一年级。如果你希望在下一步有人引路,而不是凭感觉前行,Dingrui Scholars 的导师正是沿着这条路径,以一对一辅导与小班课授课。欢迎从免费评估开始。
Common Questions常见问题
What is the difference between a list and a dictionary?列表和字典有什么区别?
A list stores items in order and accesses them by numeric index, while a dictionary stores key-value pairs and accesses values by their key. Use a dictionary when each value has a natural label, such as mapping a student ID to a grade.列表按顺序存储元素并通过数字索引访问,字典存储键值对并通过键访问值。当每个值都有一个自然标签时使用字典,比如把学号映射到成绩。
How do you loop through a 2D array?如何遍历二维数组?
A 2D array is a table of rows and columns that requires nested loops: the outer loop iterates over the rows and the inner loop iterates over the columns within each row. A single loop can only access one dimension at a time.二维数组是行与列组成的表格,需要用嵌套循环:外层循环遍历行,内层循环遍历每行中的列。单层循环一次只能访问一个维度。
What is the difference between a tuple and a list?元组和列表有什么区别?
A list is mutable, meaning you can change, add, or remove its elements, while a tuple is immutable and cannot be changed after it is created. Tuples are useful for fixed collections of values that should not change.列表是可变的,可以修改、添加或删除元素;元组是不可变的,创建后不能更改。元组适合用于不应改变的固定值集合。
Syllabus alignment & how to use this guide大纲对照与使用说明
How to use this guide如何使用本指南
Data structures appear in every curriculum mapped here, but with different emphasis. Ontario ICS3U (Grade 11) requires one-dimensional arrays with full CRUD operations; ICS4U (Grade 12) adds 2D arrays and abstract types such as stacks, queues, and dictionaries: those sections carry the Honors flag. Alberta CSE2120 (Intermediate, Grade 11-12) is the dedicated data-structures module, requiring static arrays, dynamic arrays, and records. BC Computer Programming 12 names "Uses of pre-built data structures": grade-12 only. CSTA 3B-AP-12 (Level 3B, grades 11-12) asks students to compare and contrast fundamental structures. AP CSP Big Idea 3 Topic 3.10 covers lists (AAP-2.K). Sections 1–3 (arrays, indexing, list operations) are the floor for all curricula; Sections 4–7 (2D arrays, dictionaries, tuples/sets, choosing) are core for honors/AP-track students and clearly flagged.所有对照大纲均涉及数据结构,但侧重点各有不同。安大略 ICS3U(11 年级)要求对一维数组进行完整的增删改查操作;ICS4U(12 年级)增加了二维数组和栈、队列、字典等抽象类型,这些节标有 Honors 标志。阿尔伯塔 CSE2120(中级,11-12 年级)是专门的数据结构模块,要求掌握静态数组、动态数组和记录。BC Computer Programming 12 命名"预构建数据结构的使用",仅限 12 年级。CSTA 3B-AP-12(3B 级,11-12 年级)要求学生比较和对比基本结构。AP CSP 大概念 3 主题 3.10 涵盖列表(AAP-2.K)。第 1–3 节(数组、索引、列表操作)是所有大纲的基础;第 4–7 节(二维数组、字典、元组/集合、选择)是荣誉/AP 轨道学生的核心内容,并有明确标注。
| If you are in…如果你在… | Focus on these sections重点学习 | Defer / lighter可推迟 / 减负 | Source依据 |
|---|---|---|---|
| 🇺🇸 US CSTA / AP CSP美国 CSTA / AP CSP | §1 (arrays/lists) and §2 (indexing/traversal) and §3 (list operations) directly map to AP CSP Big Idea 3 Topic 3.10 (AAP-2.K). CSTA 3A-AP-14 ("Use lists to simplify solutions") applies across §1–§3.§1(数组/列表)、§2(索引/遍历)和 §3(列表操作)直接对应 AP CSP 大概念 3 主题 3.10(AAP-2.K)。CSTA 3A-AP-14("使用列表简化解决方案")适用于 §1–§3。 | CSTA 3B-AP-12 (compare/contrast structures) and §4–§7 are Level 3B: grades 11-12 elective track. AP CSP floor students may focus on §1–§3.CSTA 3B-AP-12(比较/对比结构)和 §4–§7 属于 3B 级,11-12 年级选修轨道。AP CSP 基础学生可专注于 §1–§3。 | CSTA K-12 and AP CSP: CSTA 3B-AP-12, 3B-AP-13; AP CSP Big Idea 3 (AAP) Topic 3.10, LO AAP-2.K; CSTA 3A-AP-14:CSTA 3B-AP-12、3B-AP-13;AP CSP 大概念 3(AAP)主题 3.10、学习目标 AAP-2.K;CSTA 3A-AP-14 |
| 🇨🇦 ON Grade 11: ICS3U安大略 11 年级:ICS3U | §1 through §7 in full. ICS3U Strand B (B1, B3) explicitly names problem-solving strategies including “stepwise refinement, divide and conquer” and algorithm design. §7 tracing maps to B3.3 (algorithm testing) and B4 (software development cycle).§1 至 §7 完整学习。ICS3U B 单元(B1、B3)明确点名"逐步精化、分而治之"等解题策略和算法设计。§7 追踪对应 B3.3(算法测试)和 B4(软件开发周期)。 | §4 (2D arrays) and §5 (dictionaries) carry the Honors flag: those map to ICS4U A3.5 and C1.1 (Grade 12).§4(二维数组)和 §5(字典)标有 Honors 标志,对应 ICS4U A3.5 和 C1.1(12 年级)。 | ON/BC Computer Studies 11-12: ICS3U Strand A A1.5, A1.6; ICS4U Strand A A1.5, A3.3, A3.5; ICS4U C1.1:ICS3U A 单元 A1.5、A1.6;ICS4U A 单元 A1.5、A3.3、A3.5;ICS4U C1.1 |
| 🇨🇦 BC: CP12BC:CP12 | BC Computer Programming 12 Content (verbatim): "Uses of pre-built data structures." This is the explicit BC data-structures anchor: grade 12 only. Sections §1–§7 are all relevant.BC Computer Programming 12 内容(原文):"预构建数据结构的使用。"这是 BC 数据结构的明确依据,仅限 12 年级。第 §1–§7 节均适用。 | BC CP11 does not name arrays/lists explicitly; treating §1–§3 as foundational is appropriate from CP11 onward even without a formal CP11 standard.BC CP11 未明确命名数组/列表;尽管 CP11 没有正式标准,从 CP11 起将 §1–§3 视为基础是合适的。 | ON/BC Computer Studies 11-12: BC Computer Programming 12 "Uses of pre-built data structures":BC Computer Programming 12"预构建数据结构的使用" |
| 🇨🇦 AB: CSE2120阿尔伯塔:CSE2120 | §1 through §7. CSE2120 Data Structures 1 (Intermediate) covers static arrays, single- and double-dimensional arrays, dynamic arrays, records, and operations (create, insert, delete, search, size, copy, compare). This guide is a near-complete match for CSE2120 outcomes 1.2–1.3.§1 至 §7。CSE2120 数据结构 1(中级)涵盖静态数组、单维和双维数组、动态数组、记录以及操作(创建、插入、删除、搜索、大小、复制、比较)。本指南与 CSE2120 结果 1.2–1.3 高度匹配。 | CSE2120 is Intermediate level, so the matching sections carry the Honors flag. CSE3320 Dynamic Data Structures 1 (Advanced) extends further; that is beyond this guide's scope.CSE2120 属中级,对应各节标有 Honors 标志。CSE3320 动态数据结构 1(高级)进一步延伸;超出本指南范围。 | Alberta CTS Computing Science: CSE2120 outcomes 1.2.1, 1.2.2, 1.2.3, 1.3.1–1.3.6:CSE2120 结果 1.2.1、1.2.2、1.2.3、1.3.1–1.3.6 |
| 🇺🇸 AP CSP / AP CSA feeder trackAP CSP / AP CSA 衔接轨道 | All seven sections including going-deeper boxes. AP CSP Topic 3.10 (lists, AAP-2.K) covers list operations. AP CSA (Java) expands to arrays, ArrayList, 2D arrays, and HashMap: everything in this guide transfers directly.全部 7 节,包含深入框。AP CSP 主题 3.10(列表,AAP-2.K)涵盖列表操作。AP CSA(Java)扩展至数组、ArrayList、二维数组和 HashMap,本指南的所有内容可直接迁移。 | Nothing. Data structures are the bridge between HS CS and AP/university-level programming. Mastering this unit is required for both AP CS courses.无。数据结构是高中计算机科学与 AP/大学编程之间的桥梁。掌握本单元是两门 AP CS 课程的前提。 | CSTA K-12 and AP CSP: CSTA 3B-AP-12, 3A-AP-14; AP CSP Big Idea 3 Topic 3.10, LO AAP-2.K:CSTA 3B-AP-12、3A-AP-14;AP CSP 大概念 3 主题 3.10、学习目标 AAP-2.K |
Once you have located your row, use the two cards below to gauge how quickly you should work through the recommended sections.找到所在行后,用下面两张卡片决定推进速度。
Focus on three things: (1) what an array is and how indexing works (zero-based); (2) the three core list operations (append, insert, remove) and how to write them in pseudocode; (3) what a dictionary is and how to do a key-value lookup. Read every cram-cheat box. The flashcards at the end cover every term you are likely to be tested on.专注三件事:(1) 数组是什么以及索引如何工作(从零开始);(2) 三种核心列表操作(追加、插入、删除)以及如何用伪代码编写;(3) 字典是什么以及如何进行键值查找。读每个速记框。最后的闪卡涵盖你可能被考到的每个术语。
Work all seven sections including going-deeper boxes. Know not just what each structure does but when to use it and why. AP CSP Big Idea 3 expects fluent list manipulation. AP CSA adds 2D arrays and ArrayList: §4 is your bridge. ON ICS4U A3.5 requires algorithms on 2D arrays; AB CSE2120 requires insert/delete/search on arrays. Section 7 (choosing the right structure) is the capstone thinking skill of this unit.完成全部七节,包含深入框。不仅要知道每种结构的功能,还要知道何时使用以及原因。AP CSP 大概念 3 要求流畅操作列表。AP CSA 增加了二维数组和 ArrayList,§4 是你的桥梁。ON ICS4U A3.5 要求对二维数组进行算法操作;AB CSE2120 要求对数组进行插入/删除/搜索。第 7 节(选择正确的数据结构)是本单元的核心思维技能。