1-D arrays (lists) · 一维数组(列表)
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
A list holds many values
- A list (the exam calls it an array) stores many values under one name.
- Write the items in square brackets, separated by commas.
- An array normally stores items of the same type.
中文
列表存放许多值
- 列表(list,考试里叫数组 array)用一个名字存放许多值。
- 把元素写在方括号里,用逗号隔开。
- 数组通常存放相同类型的元素。
scores = [40, 55, 72, 90]
print(scores)
English
Reach an item by its index
- Each item has a position number called its index.
- Python counts from 0, so the first item is
scores[0].
中文
用索引取出元素
- 每个元素都有一个位置编号,叫做索引(index)。
- Python 从 0 开始数,所以第一个元素是
scores[0]。
scores = [40, 55, 72, 90]
print(scores[0]) # 40
print(scores[2]) # 72
Explore · 探索
Index and change a list · 给列表取下标并修改
Items are numbered from 0; scores[0] is the first item. · 元素从 0 开始编号;scores[0] 是第一个元素。
English
Change an item
- Assign to an index to replace that one item.
中文
修改一个元素
- 给某个索引赋值,就能替换那一个元素。
scores = [40, 55, 72, 90]
scores[1] = 99
print(scores) # [40, 99, 72, 90]
English
Length and looping
len(scores)gives how many items there are.- A
forloop visits each item in turn.
中文
长度与遍历
len(scores)给出元素的个数。for循环依次访问每个元素。
scores = [40, 55, 72, 90]
print(len(scores)) # 4
for s in scores:
print(s)
English
In the exam: arrays start at 1
- Pseudocode declares an array with a size, and usually counts from 1.
中文
在考试里:数组从 1 开始
- 伪代码声明数组时带上大小,而且通常从 1 开始数。
DECLARE Scores : ARRAY[1:4] OF INTEGER
Scores[1] ← 40
OUTPUT Scores[1]
English
Common mistakes
- Index from
0; the last item is at positionlength - 1. - Going past the end gives an index error.
中文
常见错误
- 索引从
0开始;最后一个元素在位置length - 1。 - 越过末尾会得到索引错误。
English
Now you try
- Use an index, or a loop, on each list.
- Press Check answer to test your code.
中文
现在轮到你
- 对每个列表使用索引或循环。
- 按检查答案来测试你的代码。
The list colours is set for you. Store its second item in a variable called second (remember Python counts from 0). · 列表 colours 已为你设好。把它的第二个元素存进一个名为 second 的变量(记住 Python 从 0 开始数)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Change the first · 第一个 item of the list nums to · 到 99. · 把列表 nums 的第一个元素改成 99。
Click Run to see the output here. · 点击“运行”查看此处输出。
Use a loop to add up every number in nums and store the result in total (the answer is 43). · 用循环把 nums 中的每个数字加起来,把结果存进 total(答案是 43)。
Click Run to see the output here. · 点击“运行”查看此处输出。