Skip to content

Lists and data abstraction

Python for AP CS Principles Lesson 5 2:08 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
A program often needs many values at once — a whole class of scores. 程序常常需要一次拿住很多个值——比如一整个班的分数。
One variable per value gets messy fast, and it does not scale at all. 一个值配一个变量,很快就乱套了,而且根本没法扩展。
A list holds many values under one name. 列表把很多个值收在"一个名字"底下。
That is a data abstraction: the detail is hidden so you can think about the whole thing, and you write the same code whether the list has one value or a thousand. 这就是数据抽象:细节被藏起来,让你能把它当作一个整体来想, 而且列表里是一个值还是一千个值,你写的代码都一样。
You get one item out by its index — its position. 你靠"索引"——也就是位置——把某一项取出来。
And here is the trap, so look at the cells rather than listening. 而陷阱就在这里,所以别只听,看那几个格子。
Python counts from zero, so scores zero is the first item, and minus one is the last item. Python 从 0 开始数, 所以 scores 是第一项,而 -1 是最后一项。
The AP exam's own lists count from one. AP 考试自己的列表却从 1 开始数。
Same cells, two numberings, and mixing them up is where marks go. 同样的格子,两套编号, 而把它们搞混,分就是这么丢的。
To traverse a list means to visit every item, one by one. "遍历"一个列表,意思是把每一项都走一遍。
A for-each loop hands you one item each pass, and here the running total climbs as it goes: ten, thirty, sixty. for-each 循环每一轮交给你一项, 而这里那个累加的总数就跟着往上爬:10、30、60。
Now the useful part — append can add another score to that list, and this loop still works, unchanged. 现在说有用的地方—— append 可以再往这个列表里加一个分数, 而这个循环照样能用,一个字都不用改。
That is what the abstraction buys you. 这就是抽象换来的东西。
In exam pseudocode the same list looks like this. 在考试伪代码里,同样的列表长这样。
The arrow assigns, DISPLAY prints, and FOR EACH x IN aList matches Python's for-each exactly. 箭头做赋值,DISPLAY 做打印, 而 FOR EACH x IN aList 跟 Python 的 for-each 完全对得上。
But remember the numbering: aList one is the first element on the exam, not the second. 但记住那套编号: 在考卷上 aList 是"第一"个元素,不是第二个。
That single difference is worth reading twice. 就这一条差别,值得你读两遍。
Four things to take with you. 带走四点。
One: a list groups related values under one name. 第一:列表把相关的值收在一个名字底下。
Two: that is a data abstraction — detail hidden, the whole kept. 第二:这就是数据抽象——细节藏起来,整体留下来。
Three: in Python the first item is index zero and the last is minus one. 第三:在 Python 里第一项的索引是 0,最后一项是 -1。
Four: on the AP exam the first item is index 1. 第四:在 AP 考卷上第一项的索引是 1。
Now build and traverse a list in the tasks below. 现在去下面的题里建一个列表并遍历它。

Log in or create account

IGCSE, A-Level & AP