High School Computer Science

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 follow real exam scenarios 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 的真实考试场景。

7 sections7 节内容 US CSTA · AP CSP · ON · BC · ABUS CSTA · AP CSP · ON · BC · AB Pseudocode + Python worked examples伪代码 + Python 例题

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 at the exam level (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 — 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) is directly assessed. 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.找到所在行后,用下面两张卡片决定推进速度。

!
If you are cramming the night before如果你在临阵磨枪

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) 字典是什么以及如何进行键值查找。读每个速记框。最后的闪卡涵盖你可能被考到的每个术语。

*
If you are going for the top mark如果你目标顶分

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 (30–35% of exam) 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 tested at the highest level.完成全部七节,包含深入框。不仅要知道每种结构的功能,还要知道何时使用以及原因。AP CSP 大概念 3(占考试 30–35%)要求流畅操作列表。AP CSA 增加了二维数组和 ArrayList——§4 是你的桥梁。ON ICS4U A3.5 要求对二维数组进行算法操作;AB CSE2120 要求对数组进行插入/删除/搜索。第 7 节(选择正确的数据结构)是最高层次评估的核心思维技能。

Honors note.荣誉说明。 Sections 4 (2D arrays), 5 (dictionaries), and 6 (tuples/sets) carry the Honors chip where they map to Grade-12 or Intermediate/Advanced curriculum content. Section 7 (choosing) is conceptually Honors-level but is included in full because AP CSP also assesses it via Topic 3.10. ICS3U and AP CSP floor students should complete §1–§3 fully and attempt §4–§7 as enrichment.第 4 节(二维数组)、第 5 节(字典)和第 6 节(元组/集合)在对应 12 年级或中级/高级课程内容时标有 Honors 标志。第 7 节(选择)概念上属于荣誉级别,但完整收录,因为 AP CSP 通过主题 3.10 也会评测该内容。ICS3U 和 AP CSP 基础学生应完整学习 §1–§3,并将 §4–§7 作为拓展内容。

Arrays and Lists数组与列表

The two essential facts — memorise before anything else.两个核心事实 — 优先背熟。
  • 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, list is the built-in; in Java (AP CSA), ArrayList is 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:"使用列表简化解决方案,将计算问题泛化,而不是反复使用简单变量。"
Key difference: arrays have a fixed size declared at creation; lists resize automatically. Most exam questions that say "list" mean a dynamic list. Most that say "array" mean fixed-size. Ontario ICS3U A1.5 uses "one-dimensional array" for the foundational structure; AP CSP Topic 3.10 uses "list" for both.关键区别:数组在创建时声明固定大小;列表自动调整大小。大多数考题中"列表"指动态列表,"数组"指固定大小。安大略 ICS3U A1.5 用"一维数组"表示基础结构;AP CSP 主题 3.10 用"列表"涵盖两者。
Array anatomy数组结构

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 中则是静默内存损坏。

WE
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  — 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 要求学生描述元素、索引和边界——这三个术语是所有数组题目的词汇。

Given temps = [15, 22, 18, 30, 27], what is the value of temps[2]?给定 temps = [15, 22, 18, 30, 27]temps[2] 的值是什么?
§1 · Q1
2222
1818
3030
1515
Zero-based indexing: index 0 = 15, index 1 = 22, index 2 = 18. The third element has index 2, not 3.从零开始索引:索引 0 = 15,索引 1 = 22,索引 2 = 18。第三个元素的索引是 2,不是 3。
Remember: index 0 is the first element. Index 2 is the third element (18), not the second or fourth.记住:索引 0 是第一个元素。索引 2 是第三个元素(18),不是第二个或第四个。
Which statement best describes the difference between an array and a list?以下哪项最能描述数组与列表的区别?
§1 · Q2
An array stores strings; a list stores numbers.数组存储字符串;列表存储数字。
An array uses keys; a list uses indexes.数组使用键;列表使用索引。
An array has a fixed size declared at creation; a list can grow or shrink dynamically.数组在创建时声明固定大小;列表可以动态增长或缩小。
Arrays are ordered; lists are unordered.数组是有序的;列表是无序的。
The defining difference: static arrays have a fixed size; dynamic lists (Python list, Java ArrayList) resize as needed. Both are ordered and indexed by integer position.决定性区别:静态数组大小固定;动态列表(Python list、Java ArrayList)按需调整大小。两者都是有序的,并通过整数位置索引。
Both arrays and lists can hold any data type; both use integer indexes; both are ordered. The key difference is fixed size (array) vs. dynamic size (list).数组和列表都可以存储任意数据类型;两者都使用整数索引;两者都是有序的。关键区别是固定大小(数组)与动态大小(列表)。
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 级内容。


Indexing and Traversal索引与遍历

Indexing and traversal — two operations you must know cold.索引与遍历 — 必须熟练掌握的两种操作。
  • 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 for loop. 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:"编写带嵌套结构的算法(如计算数组中的元素、计算总和、找最高或最低值、或执行线性搜索)。"
Common patterns to memorise: sum all elements (accumulate into a total); find the maximum (track running max); find an element (linear search — return index or -1). AP CSP Topic 3.10 (AAP-2.K) requires all three.必背常用模式:求所有元素之和(累加到总计);找最大值(跟踪当前最大值);查找元素(线性搜索——返回索引或 -1)。AP CSP 主题 3.10(AAP-2.K)要求掌握全部三种。
WE
Worked Example 2 · Traversal patterns on a list of scores例题 2 · 对成绩列表的遍历模式

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 不同。两种都正确;当你需要位置而不仅仅是值时,必须使用基于索引的方式。

Given data = [10, 20, 30, 40, 50], what is the output of the following code?
total = 0
for i in range(0, 3):
    total += data[i]
print(total)
给定 data = [10, 20, 30, 40, 50],以下代码的输出是什么?
total = 0
for i in range(0, 3):
    total += data[i]
print(total)
§2 · Q1
6060
150150
9090
100100
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]=10data[1]=20data[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。
What is the last valid index for a list of length 8?长度为 8 的列表最后一个有效索引是什么?
§2 · Q2
88
99
66
77
With zero-based indexing, a list of length 8 has indices 0 through 7. The last valid index is always len(list) - 1 = 8 - 1 = 7. Accessing index 8 raises an IndexError.使用从零开始的索引,长度为 8 的列表索引为 0 到 7。最后一个有效索引始终为 len(list) - 1 = 8 - 1 = 7。访问索引 8 会引发 IndexError。
Zero-based indexing: first element is index 0, last element is index length-1. For length 8: last index = 7.从零开始的索引:第一个元素是索引 0,最后一个元素是索引"长度-1"。对于长度 8:最后一个索引 = 7。
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 开始。


List Operations: Append, Insert, Remove列表操作:追加、插入、删除

Three core mutation operations — know all three.三种核心变更操作 — 全部掌握。
  • 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) 按索引删除并返回该值。
AP CSP AAP-2.K explicitly lists: INSERT, APPEND, REMOVE, and LENGTH as the four required list operations for the AP CSP exam. Know all four.AP CSP AAP-2.K 明确列出:INSERT(插入)、APPEND(追加)、REMOVE(删除)和 LENGTH(长度)是 AP CSP 考试要求的四种列表操作。全部掌握。
WE
Worked Example 3 · Building and modifying a shopping list例题 3 · 构建和修改购物清单

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.

After executing the following, what is nums?
nums = [1, 2, 3, 4]
nums.insert(2, 99)
执行以下代码后,nums 是什么?
nums = [1, 2, 3, 4]
nums.insert(2, 99)
§3 · Q1
[1, 2, 3, 99, 4][1, 2, 3, 99, 4]
[1, 99, 2, 3, 4][1, 99, 2, 3, 4]
[1, 2, 99, 3, 4][1, 2, 99, 3, 4]
[99, 1, 2, 3, 4][99, 1, 2, 3, 4]
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]。
Which Python method removes the first occurrence of a specific value from a list?哪种 Python 方法从列表中删除特定值的第一次出现?
§3 · Q2
list.pop(value)list.pop(value)
list.remove(value)list.remove(value)
list.delete(value)list.delete(value)
del list[value]del list[value]
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) 按位置删除。了解区别——考题经常测试这一区别。

2D Arrays and Nested Lists Honors二维数组与嵌套列表 Honors

A 2D array is a table: rows and columns, two indexes.二维数组是一张表格:行和列,两个索引。
  • 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:"创建处理二维数组元素的算法。"
AB CSE2120 outcome 1.2.1 names "double dimensional arrays (tables)" explicitly. AP CSA covers 2D arrays as a required topic. BC CP12 "Uses of pre-built data structures" applies here.AB CSE2120 结果 1.2.1 明确命名"双维数组(表格)"。AP CSA 将二维数组作为必考主题。BC CP12"预构建数据结构的使用"在此适用。
WE
Worked Example 4 · A classroom grade grid例题 4 · 课堂成绩网格

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.

Given 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] 是什么?
§4 · Q1
33
44
11
77
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。
First index = row (0-indexed), second index = column. Row 2 = [7,8,9], column 0 of that row = 7.第一个索引 = 行(从 0 开始),第二个索引 = 列。第 2 行 = [7,8,9],该行的第 0 列 = 7。
Which code structure is used to visit every element in a 2D array?哪种代码结构用于访问二维数组中的每个元素?
§4 · Q2
A loop inside a loop (nested loops)循环内的循环(嵌套循环)
A single for loop单个 for 循环
A while loop only仅限 while 循环
A recursive function递归函数
A 2D array requires nested loops: the outer loop iterates over rows, the inner loop iterates over columns within each row. A single loop can only access one dimension at a time.二维数组需要嵌套循环:外层循环遍历行,内层循环遍历每行中的列。单个循环一次只能访问一个维度。
To visit every cell in a grid, you need two loops: one for rows, one for columns. This nested-loop pattern is the standard 2D traversal.要访问网格中的每个单元格,你需要两个循环:一个用于行,一个用于列。这种嵌套循环模式是标准的二维遍历。
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 中字典结构的前身。


Dictionaries and Maps (Key-Value Pairs) Honors字典与映射(键值对) Honors

A dictionary stores key-value pairs — look up any value instantly by its key.字典存储键值对——通过键立即查找任意值。
  • 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 将"字典"列为抽象数据类型。
Python uses 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 使用 dictAB CSE2120 结果 1.2.1 提到"并行数组(查找或关联表)"——字典是现代等价物。AP CSA 使用 HashMap
WE
Worked Example 5 · Student grade dictionary例题 5 · 学生成绩字典

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.

What distinguishes a dictionary from a list?字典与列表有何区别?
§5 · Q1
A dictionary uses keys to access values; a list uses integer indexes.字典使用键访问值;列表使用整数索引。
A dictionary is ordered; a list is unordered.字典是有序的;列表是无序的。
A dictionary can only store strings.字典只能存储字符串。
A dictionary is fixed-size; a list is dynamic.字典是固定大小的;列表是动态的。
The fundamental difference: lists use consecutive integer indexes (0, 1, 2, …); dictionaries use arbitrary keys to access values. Both can grow dynamically in Python.根本区别:列表使用连续整数索引(0、1、2……);字典使用任意键访问值。在 Python 中两者都可以动态增长。
The core distinction is key (dictionary) vs. integer index (list). Both are dynamic and can hold any type as values.核心区别是键(字典)vs 整数索引(列表)。两者都是动态的,值可以是任何类型。
Given d = {"x": 10, "y": 20, "z": 30}, what is d["y"]?给定 d = {"x": 10, "y": 20, "z": 30}d["y"] 是什么?
§5 · Q2
1010
"y""y"
2020
3030
d["y"] returns the value associated with key "y": 20. The key is "y"; the value is 20.d["y"] 返回键 "y" 对应的值:20。键是 "y";值是 20。
Dictionary lookup returns the value, not the key. d["y"] returns 20.字典查找返回值,不是键。d["y"] 返回 20。

Tuples and Sets元组与集合

Two more collection types — each fills a specific niche.另外两种集合类型 — 各有特定用途。
  • 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} or set().无序唯一元素集合。自动删除重复项。快速成员测试和集合运算(并集、交集、差集)。Python 语法:{x, y}set()
CSTA 3B-AP-12 Descriptive Statement lists "stacks, and queues" alongside lists and arrays. BC CP12 "Uses of pre-built data structures" covers tuples and sets.CSTA 3B-AP-12 描述性声明在列表和数组旁列举"栈和队列"等。BC CP12"预构建数据结构的使用"涵盖元组和集合。
WE
Worked Example 6 · Tuples and sets in practice例题 6 · 元组与集合实战

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)         # {65, 74, 85, 90}
print(85 in unique)   # True
print(100 in unique)  # False

classA = {"Alice", "Bob", "Carol"}
classB = {"Bob", "Dave", "Carol"}
print(classA & classB)   # {"Bob", "Carol"}
print(classA | classB)   # all four
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.

Which structure would you use to store students who have submitted an assignment, if you frequently check whether a given student has submitted?如果你频繁需要检查某个学生是否已提交作业,应使用哪种结构?
§6 · Q1
A 2D array二维数组
A tuple元组
A list列表
A set集合
A set is ideal: in is O(1) on average vs O(n) for a list; sets automatically prevent duplicates; no ordering needed.集合最理想:in 平均 O(1),而列表 O(n);自动防止重复;不需要排序。
For fast membership testing and automatic deduplication, use a set. Lists require O(n) linear search; tuples are immutable; 2D arrays are for grid data.快速成员测试和自动去重,选集合。列表需要 O(n) 搜索;元组不可变;二维数组用于网格数据。
A tuple differs from a list primarily because a tuple is:元组与列表的主要区别在于元组是:
§6 · Q2
Unordered无序的
Immutable (cannot be changed after creation)不可变的(创建后不能更改)
Only able to hold strings只能存储字符串
Accessed by key, not by index通过键而非索引访问
A tuple is immutable: once created, you cannot add, remove, or change its elements. A list is mutable. Both are ordered and indexed by integer position.元组是不可变的:创建后不能添加、删除或更改元素。列表是可变的。两者都是有序的,通过整数位置索引。
Tuples are ordered; they hold any type; they are indexed by position. The defining difference is immutability.元组是有序的;可以存储任何类型;通过位置索引。决定性区别是不可变性。

Choosing the Right Data Structure选择合适的数据结构

Match the problem to the 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.— 相关值的固定、不可变组合。
CSTA 3B-AP-12: "Compare and contrast fundamental data structures and their uses." A well-designed program picks the right structure for each piece of data.CSTA 3B-AP-12:"比较和对比基本数据结构及其用途。"设计良好的程序为每个数据片段选择正确的结构。
Structure结构 Ordered?有序? Mutable?可变? Duplicates?允许重复? Best for最适合
List列表YesYesYesSequences, ordered data序列、有序数据
2D array二维数组YesYesYesGrids, tables, images网格、表格、图像
Dictionary字典Yes (Py 3.7+)是(Py 3.7+)YesKeys: No键:否Labelled data, fast lookup带标签数据、快速查找
Set集合NoYesNoUnique items, set ops唯一项目、集合运算
Tuple元组YesNoYesFixed records, return values固定记录、返回值
You need to count how many times each word appears in a document. Which data structure is most appropriate?你需要统计文档中每个单词出现的次数。哪种数据结构最合适?
§7 · Q1
A 2D array二维数组
A set集合
A tuple per word每词一个元组
A dictionary mapping each word to its count将每个单词映射到其计数的字典
A dictionary (word → count) is natural: words are keys, counts are values. Updating a count is O(1). A set tracks presence but not count; tuples are immutable; 2D arrays need a custom key-lookup mechanism.字典(单词→计数)最自然:单词是键,计数是值。更新计数是 O(1)。集合跟踪存在性但不跟踪计数;元组不可变;二维数组需要自定义键查找。
To associate a label with a value and update it frequently, use a dictionary. word_counts["hello"] += 1 is the canonical pattern.将标签与值关联并频繁更新,选字典。word_counts["hello"] += 1 是典型模式。
A chess board’s squares are identified by row (0–7) and column (0–7). Which structure fits best?棋盘方格通过行(0–7)和列(0–7)标识。哪种结构最合适?
§7 · Q2
A 2D array (8×8)二维数组(8×8)
A set of tuples元组的集合
A dictionary with string keys以字符串为键的字典
A 1D list of 64 items64 项的一维列表
A chess board is a classic 8×8 grid. A 2D array board[row][col] maps directly to the physical layout and gives O(1) access.棋盘是经典的 8×8 网格。二维数组 board[row][col] 直接映射物理布局,提供 O(1) 访问。
When data has a natural row-column structure with integer coordinates, a 2D array is the right choice.当数据具有带整数坐标的自然行列结构时,二维数组是正确选择。

Exam Strategy and Common Pitfalls考试策略与常见陷阱

Choosing and naming structures选择和命名数据结构
  • 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 justification earns partial credit at best.在考试中被要求选择数据结构时,始终给出理由:"我使用字典,因为按学生姓名查找是 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 能力要求。
Indexing and traversal errors (§1–§3)索引和遍历错误(§1–§3)
  • 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)。在被问及数组代码中的错误类型时明确说明这一点。
2D arrays, dicts, sets (§4–§6)二维数组、字典、集合(§4–§6)
  • 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 AP CSP/CSA exam gotcha: d[(1,2)] = "A1" works; d[[1,2]] = "A1" raises TypeError.在 Python 中,元组(不可变)可以是字典键;列表(可变)不能。这是常见的 AP CSP/CSA 考试陷阱:d[(1,2)] = "A1" 有效;d[[1,2]] = "A1" 引发 TypeError。
Answer hygiene作答规范
  • 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() not add(); remove(value) not delete(value); pop(index) to remove by position. Getting the method name wrong in a written exam drops marks even if the logic is correct.append() 不是 add()remove(value) 不是 delete(value)pop(index) 按位置删除。在笔试中写错方法名会丢分,即使逻辑正确。

Flashcards闪卡

0 / 12 flipped0 / 12 已翻
data structure数据结构
A way of organising information in memory so it can be stored, retrieved, and modified efficiently. Examples: array, list, dict, set, tuple.在内存中组织信息的方式,使其能高效存储、检索和修改。示例:数组、列表、字典、集合、元组。
array — key property数组 — 关键属性
Fixed size, same element type, contiguous memory. Access by integer index (0-based in Python/Java). Bounds: 0 to length−1.固定大小,元素类型相同,连续内存。通过整数索引访问(Python/Java 从零开始)。边界:0 到"长度-1"。
index — first element?索引 — 第一个元素?
Index 0 in Python/Java (zero-based). Index 1 in AP CSP pseudocode (one-based). Last valid index = length − 1 (Python).Python/Java 中索引 0(从零开始)。AP CSP 伪代码中索引 1(从一开始)。最后有效索引 = 长度 − 1(Python)。
traversal遍历
Visiting every element in a collection exactly once, typically using a for loop. Accumulate, find max, linear search are all traversal patterns.恰好访问集合中每个元素一次,通常用 for 循环。累加、找最大值、线性搜索都是遍历模式。
list.append() vs list.insert()append() vs insert()
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 要求掌握两者。
list.remove() vs list.pop()remove() vs pop()
remove(value) deletes first occurrence of value. pop(index) removes by position and returns the element.remove(value) 删除第一次出现的值。pop(index) 按位置删除并返回该元素。
2D array access二维数组访问
grid[row][col]. Row index first, column index second. Traverse with nested loops: outer for rows, inner for columns.grid[row][col]。先行索引,后列索引。用嵌套循环遍历:外层遍历行,内层遍历列。
dictionary — key-value pair字典 — 键值对
A mapping of unique keys to values. 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) 查找。
tuple — defining trait元组 — 定义特征
Immutable ordered sequence. Cannot be changed after creation. Use for fixed records, coordinates, dict keys. Python: (x, y).不可变的有序序列。创建后不能更改。用于固定记录、坐标、字典键。Python:(x, y)
set — two key properties集合 — 两个关键属性
Unordered, unique elements. No duplicates. Fast membership test: x in s is O(1). Set ops: & intersection, | union, - difference.无序,唯一元素。无重复。快速成员测试:x in s 是 O(1)。集合运算:& 交集,| 并集,- 差集。
Choosing: word-count program?选择:词频统计程序?
Dictionary (word → count). Keys are words (strings), values are counts (ints). counts["hello"] += 1. O(1) per update.字典(单词→计数)。键是单词(字符串),值是计数(整数)。counts["hello"] += 1。每次更新 O(1)。
Choosing: chess board?选择:棋盘?
2D array board[row][col]. Natural row-column grid. O(1) access. Traverse all squares with nested loops.二维数组 board[row][col]。自然的行列网格。O(1) 访问。用嵌套循环遍历所有方格。

Practice Quiz综合测验

Given items = ["pen", "book", "ruler", "eraser"], what is len(items)?给定 items = ["pen", "book", "ruler", "eraser"]len(items) 是什么?
Q1
33
44
55
00
len() returns the number of elements. The list has 4 elements. Last valid index = 4 − 1 = 3.len() 返回元素数量。列表有 4 个元素。最后有效索引 = 4 − 1 = 3。
Count the elements: "pen", "book", "ruler", "eraser" = 4 elements. len() counts elements, not the last index.数元素:"pen"、"book"、"ruler"、"eraser" = 4 个元素。len() 计算元素数量,不是最后一个索引。
After nums = [10, 20, 30] then nums.append(40), what is nums?执行 nums = [10, 20, 30] 然后 nums.append(40) 后,nums 是什么?
Q2
[40, 10, 20, 30][40, 10, 20, 30]
[10, 40, 20, 30][10, 40, 20, 30]
[10, 20, 30, 40][10, 20, 30, 40]
[10, 20, 30][10, 20, 30]
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) 在开头添加。
Given grid = [[1,2],[3,4],[5,6]], what is grid[1][0]?给定 grid = [[1,2],[3,4],[5,6]]grid[1][0] 是什么?
Q3
11
22
44
33
grid[1] = [3, 4] (second row). grid[1][0] = 3 (first element of that row).grid[1] = [3, 4](第二行)。grid[1][0] = 3(该行第一个元素)。
First index picks the row: row 1 = [3,4]. Second index picks the column within that row: col 0 = 3.第一个索引选行:第 1 行 = [3,4]。第二个索引在该行中选列:第 0 列 = 3。
A program needs to map each student ID (integer) to their grade (string "A"/"B"/"C"). Which structure is most natural?程序需要将每个学生 ID(整数)映射到其成绩(字符串 "A"/"B"/"C")。哪种结构最自然?
Q4
A dictionary {student_id: grade}字典 {学生ID: 成绩}
A 2D array二维数组
A set of tuples元组的集合
A list of grades only仅成绩的列表
A dictionary is the natural key-value structure: student_id is the key, grade is the value. O(1) lookup. Ontario ICS4U C1.1 names "dictionary" as an ADT for exactly this use case.字典是天然的键值结构:学生 ID 是键,成绩是值。O(1) 查找。安大略 ICS4U C1.1 将"字典"列为 ADT,正是针对此用例。
When you need to pair a label/ID with a value and look it up by label, use a dictionary. A list only works by integer position, not by arbitrary ID.当你需要将标签/ID 与值配对并通过标签查找时,使用字典。列表只能按整数位置工作,不能按任意 ID。
Which CSTA standard explicitly names "arrays, stacks, and queues" as example data structures to compare and contrast? 🇺🇸 CSTA哪个 CSTA 标准明确将"数组、栈和队列"列为比较和对比的示例数据结构?🇺🇸 CSTA
Q5
3A-AP-14
3B-AP-12
3A-AP-17
3A-AP-13
CSTA 3B-AP-12 (verbatim): "Compare and contrast fundamental data structures and their uses." Descriptive Statement: "Examples could include strings, lists, arrays, stacks, and queues."CSTA 3B-AP-12(原文):"比较和对比基本数据结构及其用途。"描述性声明:"示例可包括字符串、列表、数组、栈和队列。"
3B-AP-12 = compare/contrast data structures. 3A-AP-14 = use lists to simplify. 3A-AP-17 = decompose problems. 3A-AP-13 = prototypes using algorithms.3B-AP-12 = 比较/对比数据结构。3A-AP-14 = 使用列表简化。3A-AP-17 = 分解问题。3A-AP-13 = 使用算法的原型。
You have a list [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 方法是什么?
Q6
Sort the list and count manually对列表排序并手动计数
Use a 2D array使用二维数组
Use a dictionary使用字典
len(set([5, 2, 5, 8, 2, 3])) → 4len(set([5, 2, 5, 8, 2, 3])) → 4
set() removes duplicates: {2, 3, 5, 8}. len() counts: 4 distinct values. This is the idiomatic Python one-liner for counting unique elements.set() 去重:{2, 3, 5, 8}len() 计数:4 个不同值。这是计算唯一元素的惯用 Python 单行代码。
Converting to a set automatically deduplicates. len(set(lst)) counts distinct values in one step — the simplest approach.转换为集合会自动去重。len(set(lst)) 一步计算不同值——最简单的方法。
Which Ontario ICS course (and strand) explicitly requires algorithms on two-dimensional arrays? 🇨🇦 ON哪门安大略 ICS 课程(及其单元)明确要求对二维数组进行算法操作?🇨🇦 ON
Q7
ICS4U strand A (A3.5) — Grade 12ICS4U A 单元(A3.5)— 12 年级
ICS3U strand B (B3.1) — Grade 11ICS3U B 单元(B3.1)— 11 年级
ICS3U strand A (A1.5) — Grade 11ICS3U A 单元(A1.5)— 11 年级
ICS2O — Grade 10ICS2O — 10 年级
ICS4U A3.5 (verbatim): "create algorithms to process elements in two-dimensional arrays (e.g., multiply each element by a constant, interchange elements, multiply matrices, process pixels in an image)." 2D arrays are Grade 12 (ICS4U) in Ontario.ICS4U A3.5(原文):"创建处理二维数组元素的算法(如将每个元素乘以常数、交换元素、矩阵相乘、处理图像像素)。"二维数组在安大略属 12 年级(ICS4U)。
ICS3U covers 1D arrays (A1.5, A1.6). 2D arrays and ADTs are ICS4U (Grade 12) in Ontario. B3.1 is about algorithm design, not 2D arrays.ICS3U 涵盖一维数组(A1.5、A1.6)。二维数组和 ADT 在安大略属 ICS4U(12 年级)。B3.1 是关于算法设计,不是二维数组。

Readiness Checklist准备就绪清单

Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。

0 / 11 mastered已掌握 0 / 11

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 CSA Unit 4 · Data Collection (ArrayList, arrays — the Java equivalents of the Python structures in this guide; 2D arrays and ArrayList are assessed on the AP CSA exam)AP CSA Unit 4 · 数据收集(ArrayList、数组——本指南 Python 结构的 Java 等价物;二维数组和 ArrayList 在 AP CSA 考试中被评测)

AP CSP Big Idea 3 Topic 3.10 (lists, AAP-2.K) is directly assessed: you must be able to trace list operations (APPEND, INSERT, REMOVE, LENGTH) on pseudocode and predict 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 级标准。