Skip to content

Arrays

Python for IGCSE CS Lesson 8 2:13 English narration · English + 中文 subtitles burned in

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

Chapters

Transcript
Suppose you have three scores. 假设你有三个分数。
You could use three variables — but then thirty scores needs thirty names, and you cannot write a loop over names. 你当然可以用三个变量—— 但三十个分数就要三十个名字,而且你没法对一堆名字写循环。
An array solves that: one name for all of them, with the values in order inside it. 数组解决了这个问题: 一个名字装下全部,值按顺序排在里面。
Python calls it a list; the exam calls it an array; they are the same thing for everything in this course. Python 管它叫 list,考卷管它叫 array; 在这门课里,它们是同一样东西。
Now the thing that costs marks on every array question. 现在说说每道数组题都会丢分的那件事。
To reach one item you give its position, called the index. 要取到某一个元素,你要给出它的位置,这叫下标。
Python numbers them from nought, so the first item is index nought. Python 从 0 开始编号,所以第一个元素的下标是 0。
But the exam numbers them from one. 而考卷从 1 开始编号。
Same four values, two different numbering systems — so read the question carefully: the second item is index one in Python, and index two on paper. 同样的四个值,两套编号—— 所以题目要看清楚: "第二个元素"在 Python 里下标是 1,在考卷上是 2。
The square brackets do two jobs. 方括号做两件事。
On the right of an equals sign they read: the value comes out. 写在等号右边,它是读取:值被取出来。
On the left it replaces the one that was there. 写在左边,它替换掉原来那个。
Same notation, opposite direction, and which one you get depends only on which side of the equals you wrote it. 同样的写法,方向相反, 而你得到哪一种,只取决于你把它写在等号的哪一边。
One warning: ask for an index past the end and the program stops with an error — the last one you can use is always the length minus one. 一个提醒: 如果你要一个越过末尾的下标,程序会直接报错停下—— 你能用的最后一个下标,永远是长度减 1。
The third task totals the whole array, and here the two notations genuinely differ. 第三道题是把整个数组求和,这里两种写法确实不一样。
The exam counts through indexes and reaches each item by number. 考卷是按下标数着走,用编号取到每个元素。
Python can walk the values directly, without an index at all. Python 可以直接遍历这些值,完全不用下标。
Both add up to the same number — but only the index version can go past the end, which is one good reason to prefer the Python form when you are allowed to. 两者加出来是同一个数—— 但只有用下标的那种写法可能越界, 这也是在允许的时候优先用 Python 写法的一个好理由。
Four things to take with you. 带走四点。
One: an array holds many values under one name. 第一:数组把很多值放在一个名字下面。
Two: an index picks one of them, and can be read or written. 第二:下标取出其中一个,既可以读,也可以写。
Three: Python counts from nought, and the exam counts from one. 第三:Python 从 0 开始编号,考卷从 1 开始。
Four: the last item is at the length minus one. 第四:最后一个元素在"长度减 1"的位置。
Now do the three tasks. 现在去做那三道题。

Log in or create account

IGCSE, A-Level & AP