5200.2.3 Lists

03 Introducing Lists

Lists 允许我们存储数据的集合在一个地方,无论多少数据。 List 是有特别顺序的 items 的集合。 在 Python 中[]表示一个 List。

访问List

通过位置的索引可以访问 List 中的元素,从 0 开始。

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[1])
print(bicycles[3])
 
# 通过-1 可以访问到最后一个元素
print(bicycles[-1]) -> 'specialized'

Modifying元素

修改元素的方法有下面这些:

  • insert
  • delete
  • pop
  • remove

delete会永久删除 List 的内容 pop 和 remove 的不同在于,pop 是根据 index 删除元素。 pop 默认删除 List 的最后一个。 pop 可以返回一个被删除的元素,保存给一个变量 remove 是根据名称删除元素,如果有多个,只能删除一个

Sort

  • sort sort 永久改变一个 List 的元素位置。 可以接受一个reverse=true的参数,进行 reverse sort。
  • sorted 如果不想要永久改变,就使用 sorted。
  • reverse reverse 是吧 List 的元素反过来排序,会永久改变 List

循环

在 python 中,用 for 语法对 List 进行循环

每一个在 for 后面的 indented line,都会被认为是在循环内部。

循环需要避免下面这些错误

  • Forgetting to Indent
  • Forgetting to Indent Additional Lines
  • Indenting Unnecessarily After the Loop
  • Forgetting the Colon

04 Working with lists

Range

使用 range 可以生成一系列 Numbers

range 的参数有三个

  • 开始
  • 结束(但不包含这个数字)
  • 每次增加的数字
    • 例:range(2, 11, 2)

数字统计

简单的数据统计方法

  • min(lists)
  • max(lists)
  • sum(lists)

列表推导(Comprehensions)

一个列表推导在一行中,包含了 for 循环和创建新元素,自动把新元素放到 List 中。

# 列表推导 Comprehensions
squares = [value**2 for value in range(1, 11)]
print(squares)

1.2.2.3 Lists 2026-02-06 06.36.42.excalidraw

⚠ Switch to EXCALIDRAW VIEW in the MORE OPTIONS menu of this document. ⚠ You can decompress Drawing data with the command palette: ‘Decompress current Excalidraw file’. For more info check in plugin settings under ‘Saving’

1.2.2.3 Lists 2026-02-06 06.36.42.excalidraw

Text Elements

squares = [value**2 for value in range(1, 11)]

  1. 生成数字 list

  2. 循环列表

  3. 循环之后的数字,按照前面的逻辑进行处理,然后塞到 List 中

Link to original

Slice

Slice 选择 List 的一部分,和 Range 一样,含头不含尾

接受的参数可以是下面的形式

  • players[0:3]
  • players[:3]
  • players[3:]
  • players[-3:]

也可以对 slice 进行循环

for player in players[:3]:
	print(player.title())

也可以借助 slice 对 list 进行浅拷贝。类似于 JS 中的复制一个新的数组。

my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')

注意,这里是浅拷贝。如果 list 中是可变的类型,修改 a,则会同时修改 b

a = [[1, 2], [3, 4]]
b = a[:]
b[0].append(99)
 
# 结果
# [[1, 2, 99], [3, 4]]
# [[1, 2, 99], [3, 4]]