计算机科学 4
第 9-13 关
📜

一维列表 (List)

One-Dimensional Lists

🔢 0号开始
🔄 自动点名
🎒

什么是列表 (List / Array)?

可以把它想象成:一排排好队的椅子

每个椅子上坐着一个人(元素),每个椅子都有一个号码(索引)。

friends = ['Joan', 'Ronan', 'Nikita']

方括号 [] 表示这是一个列表。

👩‍🦰
👱‍♂️
🧒
Friends List
0️⃣

索引:从 0 开始数!

在程序世界里,第一个位置是 0,不是 1!

items = hero.findItems()

gem0 = items[0] # 第1个
gem1 = items[1] # 第2个
gem2 = items[2] # 第3个
"0-based index: 就像数轴从0开始。"
💎
items[0]
0
💎
items[1]
1
💎
items[2]
2
鼠标悬停查看代码
📏

列表长度:len()

想知道队伍里有几个人?用 len() 函数。

enemies = hero.findEnemies()
if len(enemies) > 0:
  hero.attack(enemies[0])

安全检查:
只有当长度 > 0 时,才能去打第 0 个敌人。否则会扑空(报错)!

👾
👾
len() = 2
🛡️

防止越界 (Out of Range)

如果你想拿第 2 个宝石 items[1],必须确保至少有 2 个宝石。

items = hero.findItems()
if len(items) >= 2:
  hero.moveXY(items[1].pos.x...)
else:
  hero.say("不够两个!")
💎
[0]
[1]
Index 1 不存在!
🔄

列表需要更新

战场瞬息万变,每一轮循环都要重新“点名”。

while True:
  # 每一轮重新找
  enemies = hero.findEnemies()
  # ...
"不能拿着旧名单去点名,新同学可能刚进来,旧同学可能走了。"
📸

每一帧都是一张新快照

👉

遍历:一个个点名

while 循环加上 index 变量,可以把列表里的每个人都问候一遍。

index = 0
while index < len(friends):
  friend = friends[index]
  hero.say("Hi " + friend)
  index += 1
👉
0. Joan
1. Ronan
2. Nikita
3. Augustus
🎓

列表大师口诀

"方括号 [] 是队伍,
index 0 是排头兵。"
"len() 告诉你有多长,
while 循环挨个查!"
📜