Python 列表
Python 列表
Section titled “Python 列表”序列(Sequence)是 Python 中基本的有序集合。序列中的每个元素都有一个指定的索引,索引从 0 开始。
Python 内置的序列类型包括字符串(strings)、元组(tuples)和列表(lists)。本章重点介绍 列表,它是 Python 中最通用、最常用的数据结构之一。
什么是列表?
Section titled “什么是列表?”列表是元素的有序、可变(changeable)序列。列表通过将逗号分隔的元素放在方括号 [] 内来定义。列表中的元素可以是不同的数据类型。
# 空列表empty_list = []
# 整数列表numbers = [1, 2, 3, 4, 5]
# 字符串列表names = ["Alice", "Bob", "Charlie"]
# 包含混合数据类型的列表mixed_list = ['physics', 'chemistry', 1997, 2000]
# 嵌套列表(包含其他列表的列表)nested_list = [1, 2, ['a', 'b'], 3]
print(empty_list)print(numbers)print(names)print(mixed_list)print(nested_list)您还可以使用 list() 构造函数创建列表,这通常用于将其他可迭代对象(如元组或字符串)转换为列表。
tuple_example = (1, 2, 3)list_from_tuple = list(tuple_example)print(list_from_tuple) # 输出: [1, 2, 3]
string_example = "hello"list_from_string = list(string_example)print(list_from_string) # 输出: ['h', 'e', 'l', 'l', 'o']访问列表中的值
Section titled “访问列表中的值”使用方括号 [] 中的索引访问元素。索引从 0 开始。负数索引从末尾开始计数(-1 是最后一个元素)。切片 [start:stop:step] 的工作原理与字符串相同。
#!/usr/bin/env python3
my_list = ['physics', 'chemistry', 1997, 2000, 'math']numbers = [10, 20, 30, 40, 50, 60, 70]
# 索引print(f"my_list[0]: {my_list[0]}") # 输出: physicsprint(f"my_list[-1]: {my_list[-1]}") # 输出: math
# 切片 [start:stop]print(f"numbers[1:5]: {numbers[1:5]}") # 输出: [20, 30, 40, 50]print(f"numbers[:3]: {numbers[:3]}") # 输出: [10, 20, 30]print(f"numbers[4:]: {numbers[4:]}") # 输出: [50, 60, 70]
# 带步长的切片print(f"numbers[::2]: {numbers[::2]}") # 输出: [10, 30, 50, 70]更新列表(可变性)
Section titled “更新列表(可变性)”由于列表是可变的,您可以更改其内容。您可以通过赋值新值来更新单个元素或切片。
#!/usr/bin/env python3
my_list = ['physics', 'chemistry', 1997, 2000]print(f"Original list: {my_list}")
# 更新单个元素print(f"Value at index 2: {my_list[2]}")my_list[2] = 2001print(f"New value at index 2: {my_list[2]}")print(f"List after update: {my_list}")
# 更新一个切片my_list[1:3] = ['biology', 2023] # 替换索引 1 和 2 处的元素print(f"List after slice update: {my_list}")
# 使用切片插入元素(不移除)my_list[1:1] = ['math', 'stats'] # 在索引 1 处插入print(f"List after slice insertion: {my_list}")输出:
Original list: ['physics', 'chemistry', 1997, 2000]Value at index 2: 1997New value at index 2: 2001List after update: ['physics', 'chemistry', 2001, 2000]List after slice update: ['physics', 'biology', 2023, 2000]List after slice insertion: ['physics', 'math', 'stats', 'biology', 2023, 2000]向列表中添加元素
Section titled “向列表中添加元素”append(item):将单个item添加到列表末尾。extend(iterable):将来自iterable(如另一个列表、元组或字符串)的所有元素添加到列表末尾。insert(index, item):在指定的index处插入一个item。
示例:
numbers = [1, 2, 3]print(f"Initial list: {numbers}")
numbers.append(4)print(f"After append(4): {numbers}")
numbers.extend([5, 6])print(f"After extend([5, 6]): {numbers}")
numbers.insert(0, 0) # 在开头插入 0(索引 0)print(f"After insert(0, 0): {numbers}")输出:
Initial list: [1, 2, 3]After append(4): [1, 2, 3, 4]After extend([5, 6]): [1, 2, 3, 4, 5, 6]After insert(0, 0): [0, 1, 2, 3, 4, 5, 6]删除列表元素
Section titled “删除列表元素”几种移除元素的方式:
del list_name[index]:移除指定index处的元素。del list_name[start:stop]:移除切片。pop([index]):移除并返回指定index处的元素(默认为最后一个元素,-1)。remove(value):移除指定value的第一个匹配项。如果未找到该值,则引发ValueError。
示例:
#!/usr/bin/env python3
my_list = ['physics', 'chemistry', 1997, 2000, 'math', 1997]print(f"Original list: {my_list}")
# 使用 del 按索引删除del my_list[2] # 移除索引 2 处的元素 (1997)print(f"After del my_list[2]: {my_list}")
# 使用 pop(默认移除并返回最后一个元素)last_item = my_list.pop()print(f"Popped item: {last_item}")print(f"List after pop(): {my_list}")
# 使用 pop 带索引item_at_1 = my_list.pop(1) # 移除索引 1 处的元素 ('chemistry')print(f"Popped item at index 1: {item_at_1}")print(f"List after pop(1): {my_list}")
# 使用 remove 按值删除my_list.remove(2000)print(f"List after remove(2000): {my_list}")
# 移除第一个匹配的 1997(如果仍然存在)if 1997 in my_list: my_list.remove(1997) print(f"List after remove(1997): {my_list}")else: print("1997 not found for removal.")输出:
Original list: ['physics', 'chemistry', 1997, 2000, 'math', 1997]After del my_list[2]: ['physics', 'chemistry', 2000, 'math', 1997]Popped item: 1997List after pop(): ['physics', 'chemistry', 2000, 'math']Popped item at index 1: chemistryList after pop(1): ['physics', 2000, 'math']List after remove(2000): ['physics', 'math']1997 not found for removal.基本列表操作
Section titled “基本列表操作”列表支持常见的序列操作:
| Python 表达式 | 结果 | 描述 |
|---|---|---|
len([1, 2, 3]) | 3 | 长度:元素数量 |
[1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | 连接:创建一个新列表 |
['Hi!'] * 4 | [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] | 重复:创建一个包含重复元素的新列表 |
3 in [1, 2, 3] | True | 成员关系:检查元素是否存在 |
for x in [1, 2, 3]: print(x) | 1\n2\n3 | 迭代:遍历元素 |
内建列表函数与方法
Section titled “内建列表函数与方法”Python 包含专用于列表的函数和方法:
内建列表函数:
Section titled “内建列表函数:”| 函数 | 描述 |
|---|---|
len(list) | 返回列表中元素的数量。 |
max(list) | 返回具有最大值的元素(元素必须可比较)。 |
min(list) | 返回具有最小值的元素(元素必须可比较)。 |
sum(list) | 返回元素的总和(元素必须是数字)。 |
list(iterable) | 将可迭代对象(元组、字符串、集合等)转换为列表。 |
sorted(list) | 返回一个新的排序列表(原始列表不变)。 |
any(list) | 如果列表中至少一个元素为 True(或评估为 True),则返回 True。 |
all(list) | 如果列表中所有元素都为 True(或评估为 True),则返回 True。 |
列表方法(除非另有说明,否则会原地修改列表):
Section titled “列表方法(除非另有说明,否则会原地修改列表):”| 方法 | 描述 |
|---|---|
list.append(obj) | 将 obj 添加到列表末尾。 |
list.extend(iterable) | 将来自 iterable 的元素追加到列表末尾。 |
list.insert(index, obj) | 在 index 处插入 obj。 |
list.remove(value) | 移除 value 的第一个匹配项。如果未找到,则引发 ValueError。 |
list.pop([index]) | 移除并返回 index 处的元素(默认:最后一个)。如果列表为空或索引超出范围,则引发 IndexError。 |
list.clear() | 移除列表中的所有元素。 |
list.index(value[, start[, end]]) | 返回 value 的第一个匹配项的索引。如果未找到,则引发 ValueError。 |
list.count(value) | 返回 value 在列表中出现的次数。 |
list.sort(key=None, reverse=False) | 原地排序列表中的元素。key 指定用于提取比较键的函数,reverse=True 用于降序排序。 |
list.reverse() | 原地反转列表中的元素。 |
list.copy() | 返回列表的浅拷贝。 |
sort() 与 sorted() 的示例:
numbers = [3, 1, 4, 1, 5, 9, 2]
# sorted() 返回一个新列表new_sorted_list = sorted(numbers)print(f"Original list: {numbers}")print(f"New sorted list: {new_sorted_list}")
# sort() 原地修改列表numbers.sort(reverse=True) # 降序排序print(f"Original list after sort(reverse=True): {numbers}")输出:
Original list: [3, 1, 4, 1, 5, 9, 2]New sorted list: [1, 1, 2, 3, 4, 5, 9]Original list after sort(reverse=True): [9, 5, 4, 3, 2, 1, 1]列表推导式(简洁的列表创建方式)
Section titled “列表推导式(简洁的列表创建方式)”一种强大而简洁的方式,用于基于现有可迭代对象创建列表。
语法:[expression for item in iterable if condition]
# 创建一个包含 0 到 9 的平方的列表squares = [x**2 for x in range(10)]print(f"Squares: {squares}") # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 创建一个包含 0 到 19 之间的偶数的列表even_numbers = [x for x in range(20) if x % 2 == 0]print(f"Even numbers: {even_numbers}") # 输出: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 将字符串列表转换为大写words = ['hello', 'world', 'python']upper_words = [word.upper() for word in words]print(f"Uppercase words: {upper_words}") # 输出: ['HELLO', 'WORLD', 'PYTHON']