此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
为什么用列表?
- 程序常常一次需要很多个值,比如全班的分数。
- 一个值用一个变量会很乱。
- 列表(list)用一个名字保存很多个值 —— 这是一个有用的数据抽象(data abstraction)。
什么是数据抽象?
- 抽象(abstraction)隐藏细节,让你思考整体,而不是每个部分。
- 列表让你用同样的方式处理 1 个值或 1000 个值。
- 不管列表有多长,你写的代码都一样。
创建列表并读取它
- 把元素写在方括号里:
[10, 20, 30]。 - 用索引(index,也就是位置)取出一个元素。Python 从
0开始。 scores[0]是第一个元素;scores[-1]是最后一个元素。
English
scores = [10, 20, 30]
print(scores[0])
print(scores[-1])
print(len(scores))
用 append 让列表变长
scores.append(x)把x加到列表的末尾。- 程序运行时,列表可以变长。
len(scores)告诉你现在有多少个元素。
English
scores = [10, 20]
scores.append(30)
print(scores)
print(len(scores))
遍历(访问每一个元素)
- 遍历(traverse)一个列表,就是一个接一个地走过每个元素。
for s in scores:每一轮给你一个元素 —— 这是 for-each(逐项)循环。- 这是处理整个列表的简洁方法。
English
scores = [10, 20, 30]
total = 0
for s in scores:
total = total + s
print(total)
在 AP CSP 伪代码中
- 列表也是考试中的列表——但CB列表采用1索引。
- 所以在 CB 里
aList[1]是第一个元素,而 Python 的第一个是scores[0]。 FOR EACH x IN list对应 Python 的for x in list:。DISPLAY= print,←==。
aList ← [10, 20, 30]
DISPLAY(aList[1]) ## the FIRST item (1-indexed!)
total ← 0
FOR EACH x IN aList
{
total ← total + x
}
DISPLAY(total)
常见错误
- 列表从
0开始索引;最后一个元素是a[-1]。 - 列表把相关的值归到一个名字下。
现在轮到你
- 在每个任务里创建、扩展或遍历一个列表。
- 按检查答案来测试你的代码。
探索
A list of items, indexed
A list stores many values in order, each at an 索引 from 0.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Start from the list colors = ["red", "green"]. Use .append(...) to add "blue" to the end, so the list becomes ["red", "green", "blue"].
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
nums is(是) [4, 8, 15, 16, 23]. Traverse it with a for loop to add up every value, then print the total. (It should print 66.)
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]. Store the 第一个 day in first and the 最后一段 day in last using indexing.
点击“运行”查看此处输出。