Python 列表

列表是 Python 中用于存储数据集合的 4 种数据类型之一。

# List: 有序的项目集合,用方括号括起来
['John', 'Peter', 'Debora', 'Charles']

使用索引获取值

# 使用索引访问列表元素(从 0 开始,第一个元素是索引 0)
furniture = ['table', 'chair', 'rack', 'shelf']

furniture[0]  # 返回第一个元素:'table'
'table'
furniture[1]
'chair'
furniture[2]
'rack'
furniture[3]
'shelf'

负数索引

# 负数索引:从列表末尾访问元素
furniture = ['table', 'chair', 'rack', 'shelf']

furniture[-1]  # 返回最后一个元素:'shelf'
'shelf'
furniture[-3]
'chair'
f'The {furniture[-1]} is bigger than the {furniture[-3]}'
'The shelf is bigger than the chair'
测验

登录后即可答题并追踪学习进度

如果 furniture = ['table', 'chair', 'rack', 'shelf'],那么 furniture[-1] 返回什么?
A. 'table'
B. 'shelf'
C. ['shelf']
D. IndexError

使用切片获取子列表

# 切片:使用 [start:end] 语法获取子列表(end 是不包含的)
furniture = ['table', 'chair', 'rack', 'shelf']

furniture[0:4]  # 返回索引 0 到 3 的元素(不包含 4)
['table', 'chair', 'rack', 'shelf']
furniture[1:3]
['chair', 'rack']
furniture[0:-1]
['table', 'chair', 'rack']
# 从开头切片:省略 start 索引(默认为 0)
furniture[:2]  # 返回前两个元素
['table', 'chair']
# 切片到末尾:省略 end 索引(默认为列表末尾)
furniture[1:]  # 返回从索引 1 到末尾的所有元素
['chair', 'rack', 'shelf']
furniture[:]
['table', 'chair', 'rack', 'shelf']

切片整个列表将执行复制:

# 切片创建副本:[:] 创建列表的浅拷贝
spam = ['cat', 'bat', 'rat', 'elephant']
spam2 = spam[:]  # 创建一个副本,而不是引用
spam2
['cat', 'bat', 'rat', 'elephant']
spam.append('dog')
spam
['cat', 'bat', 'rat', 'elephant', 'dog']
spam2
['cat', 'bat', 'rat', 'elephant']
测验

登录后即可答题并追踪学习进度

spam 是一个列表时,spam[:] 创建什么?
A. 对同一列表的引用
B. 一个空列表
C. 列表的浅拷贝
D. 一个反转的列表

使用 len() 获取列表长度

# len() 返回列表中项目的数量
furniture = ['table', 'chair', 'rack', 'shelf']
len(furniture)  # 返回 4
4

使用索引更改值

# 通过向索引分配新值来修改列表元素
furniture = ['table', 'chair', 'rack', 'shelf']

furniture[0] = 'desk'  # 替换第一个元素
furniture
['desk', 'chair', 'rack', 'shelf']
furniture[2] = furniture[1]
furniture
['desk', 'chair', 'chair', 'shelf']
furniture[-1] = 'bed'
furniture
['desk', 'chair', 'chair', 'bed']

拼接和复制

# 列表拼接:使用 + 运算符组合两个列表
[1, 2, 3] + ['A', 'B', 'C']  # 返回 [1, 2, 3, 'A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
# 列表复制:使用 * 运算符多次重复列表
['X', 'Y', 'Z'] * 3  # 返回 ['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
my_list = [1, 2, 3]
my_list = my_list + ['A', 'B', 'C']
my_list
[1, 2, 3, 'A', 'B', 'C']

使用 for 循环处理列表

# 使用 for 循环遍历列表元素
furniture = ['table', 'chair', 'rack', 'shelf']

for item in furniture:  # 遍历每个项目
    print(item)
table
chair
rack
shelf

使用 enumerate() 在循环中获取索引

# enumerate() 在循环中同时返回索引和值
furniture = ['table', 'chair', 'rack', 'shelf']

for index, item in enumerate(furniture):  # 一起获取索引和项目
    print(f'index: {index} - item: {item}')
index: 0 - item: table
index: 1 - item: chair
index: 2 - item: rack
index: 3 - item: shelf

使用 zip() 在多个列表中循环

# zip() 按元素将多个列表组合在一起进行循环
furniture = ['table', 'chair', 'rack', 'shelf']
price = [100, 50, 80, 40]

for item, amount in zip(furniture, price):  # 配对两个列表中的元素
    print(f'The {item} costs ${amount}')
The table costs $100
The chair costs $50
The rack costs $80
The shelf costs $40

in 和 not in 运算符

# in 运算符:检查一个项目是否存在于列表中
'rack' in ['table', 'chair', 'rack', 'shelf']  # 返回 True
True
'bed' in ['table', 'chair', 'rack', 'shelf']
False
furniture = ['table', 'chair', 'rack', 'shelf']
'bed' not in furniture
True
'rack' not in furniture
False

多重赋值技巧

多重赋值技巧是一种快捷方式,允许您在一行代码中用列表中的值给多个变量赋值。所以,与其这样做:

furniture = ['table', 'chair', 'rack', 'shelf']
table = furniture[0]
chair = furniture[1]
rack = furniture[2]
shelf = furniture[3]

您可以输入这一行代码:

furniture = ['table', 'chair', 'rack', 'shelf']
table, chair, rack, shelf = furniture

table
'table'
chair
'chair'
rack
'rack'
shelf
'shelf'

多重赋值技巧也可以用来交换两个变量的值:

a, b = 'table', 'chair'
a, b = b, a
print(a)
chair
print(b)
table

index 方法

index 方法允许您通过传递其名称来查找值的索引:

furniture = ['table', 'chair', 'rack', 'shelf']
furniture.index('chair')
1

添加值

append()

append 将一个元素添加到 list 的末尾:

furniture = ['table', 'chair', 'rack', 'shelf']
furniture.append('bed')
furniture
['table', 'chair', 'rack', 'shelf', 'bed']
测验

登录后即可答题并追踪学习进度

append() 方法对列表做什么?
A. 将一个元素添加到列表的末尾
B. 将一个元素添加到列表的开头
C. 替换最后一个元素
D. 移除最后一个元素

insert()

insert 在给定位置向 list 添加一个元素:

furniture = ['table', 'chair', 'rack', 'shelf']
furniture.insert(1, 'bed')
furniture
['table', 'bed', 'chair', 'rack', 'shelf']

移除值

del

del 使用索引移除一个项:

furniture = ['table', 'chair', 'rack', 'shelf']
del furniture[2]
furniture
['table', 'chair', 'shelf']
del furniture[2]
furniture
['table', 'chair']

remove()

remove 使用其实际值移除一个项:

furniture = ['table', 'chair', 'rack', 'shelf']
furniture.remove('chair')
furniture
['table', 'rack', 'shelf']

移除重复项

如果该值在列表中出现多次,则只移除该值的第一个实例。

pop()

默认情况下,pop 将移除并返回列表的最后一个项。您也可以将元素的索引作为可选参数传递:

animals = ['cat', 'bat', 'rat', 'elephant']

animals.pop()
'elephant'
animals
['cat', 'bat', 'rat']
animals.pop(0)
'cat'
animals
['bat', 'rat']
测验

登录后即可答题并追踪学习进度

调用列表上的 pop() 会做什么?
A. 只移除最后一项
B. 移除并返回一项(默认最后一个,或指定的索引)
C. 只返回最后一项而不移除它
D. 移除列表中的所有项

使用 sort() 对值进行排序

numbers = [2, 5, 3.14, 1, -7]
numbers.sort()
numbers
[-7, 1, 2, 3.14, 5]
furniture = ['table', 'chair', 'rack', 'shelf']
furniture.sort()
furniture
['chair', 'rack', 'shelf', 'table']

您也可以为 reverse 关键字参数传递 True,以便 sort() 以相反的顺序对值进行排序:

furniture.sort(reverse=True)
furniture
['table', 'shelf', 'rack', 'chair']

如果您需要按常规字母顺序对值进行排序,请在 sort() 方法调用中为 key 关键字参数传递 str.lower

letters = ['a', 'z', 'A', 'Z']
letters.sort(key=str.lower)
letters
['a', 'A', 'z', 'Z']

您可以使用内置函数 sorted 来返回一个新列表:

furniture = ['table', 'chair', 'rack', 'shelf']
sorted(furniture)
['chair', 'rack', 'shelf', 'table']

Tuple 数据类型

元组与列表

元组和列表之间的关键区别在于,元组不可变对象,而列表可变对象。这意味着元组不能被更改,而列表可以被修改。元组比列表更节省内存。

furniture = ('table', 'chair', 'rack', 'shelf')

furniture[0]
'table'
furniture[1:3]
('chair', 'rack')
len(furniture)
4

元组与列表的主要区别在于,元组像字符串一样是不可变的。

在 list() 和 tuple() 之间转换

tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
list(('cat', 'dog', 5))
['cat', 'dog', 5]
list('hello')
['h', 'e', 'l', 'l', 'o']
测验

登录后即可答题并追踪学习进度

Python 中列表和元组的主要区别是什么?
A. 列表只能包含数字,元组可以包含任何内容
B. 元组创建速度更快
C. 列表是可变的(可以更改),元组是不可变的(不能更改)
D. 列表使用方括号,元组使用花括号

相关链接