此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
列表存放许多值
- 列表(list)在一个变量里存放很多值。
- 把这些项写在方括号里:
[10, 20, 30]。 - 这些项可以是数字、字符串,或两者混合。
获取和修改元素
- 用索引,就像字符串一样:
nums[0]是第一个元素。 nums[-1]是最后一个元素。- 你也可以修改某个元素:
nums[0] = 99。
English
fruits = ["apple", "pear", "plum"]
print(fruits[0])
print(fruits[-1])
添加元素并计数
nums.append(x)把x加到列表的末尾。len(nums)告诉你有多少个元素。- 列表可以在程序运行时不断增长。
English
fruits = ["apple", "pear"]
fruits.append("plum")
print(len(fruits))
print(fruits)
遍历列表
for item in nums:依次访问每个元素。- 循环变量每一轮保存一个元素。
- 这是处理每个值的简便方法。
English
scores = [10, 20, 30]
total = 0
for s in scores:
total = total + s
print(total)
用剑桥伪代码表示
- 列表就是考试里的一维数组(1-D array)。注意:考试里的数组常常从索引
1开始,而 Python 列表从0开始。
DECLARE Scores : ARRAY[1:3] OF INTEGER
Scores[1] ← 10
Scores[2] ← 20
Scores[3] ← 30
FOR I ← 1 TO 3
OUTPUT Scores[I]
NEXT I
常见错误
- 第一个元素是
a[0],最后一个是a[-1];a[len(a)]会越界。 b = a共享同一个列表。a.copy()创建一个新的外层列表,但嵌套的可变项仍被共享:这是浅拷贝。append在末尾加一个元素。
现在轮到你
- 每个任务都要构建或遍历一个列表。
- 按检查答案来测试你的代码。
探索
A list changes in place
A list is ordered and indexed; append/change/pop all modify it.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Create a list colors holding "red", "green", "blue". Then append "yellow" so the list has four items.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Loop over the list nums and add up its values. Store the total in total (the answer is 66).
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Find the largest value in nums with a loop. Start largest at the first item, then loop through nums and keep the bigger value. Store the answer in largest (it is 23).
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Build a 新的 列表 backwards with the items of nums in reverse order. Use a loop, and do not change nums itself.
点击“运行”查看此处输出。