Python列表操作完全指南

1. 列表简介

Python列表是一种有序、可变的数据结构,它能够存储任意数量的元素,且支持不同类型的元素共存。列表使用方括号[]表示,元素之间用逗号分隔。作为Python中最常用的数据类型之一,列表提供了丰富的操作方法,是数据分析和算法实现的基础工具。列表的有序性意味着元素按插入顺序排列,可变性则允许在创建后进行修改、增加或删除元素。

# 创建一个包含不同类型元素的列表
sample_list = [1, "Hello", 3.14, True, [1, 2, 3]]
print("示例列表:", sample_list)
print("列表长度:", len(sample_list))  # 输出列表元素数量

列表的特点:

有序性:元素保持插入顺序,可通过索引访问

异构性:可同时存储不同类型的数据

可变性:创建后可以动态修改内容

嵌套性:可以包含其他列表作为元素

2. 创建列表

2.1. 基本创建方式

最直接的方式是使用方括号将元素包围,元素间用逗号分隔。

# 创建空列表
empty_list = []
print("空列表:", empty_list)

# 创建包含相同类型元素的列表
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]

# 创建包含不同类型元素的列表
mixed = [1, "text", 3.14, False]
print("数字列表:", numbers)
print("水果列表:", fruits)
print("混合列表:", mixed)

2.2. 使用list()构造函数

list()构造函数可以将其他可迭代对象(如字符串、元组、集合等)转换为列表。

# 将字符串转换为列表(每个字符作为一个元素)
text = "Python"
char_list = list(text)
print("字符列表:", char_list)  # 输出: ['P', 'y', 't', 'h', 'o', 'n']

# 将元组转换为列表
numbers_tuple = (1, 2, 3)
numbers_list = list(numbers_tuple)
print("元组转列表:", numbers_list)  # 输出: [1, 2, 3]

# 将字典转换为列表(仅转换键)
dict_sample = {"a": 1, "b": 2}
dict_keys = list(dict_sample)
print("字典键列表:", dict_keys)  # 输出: ['a', 'b']

2.3. 列表推导式创建

列表推导式是一种高效创建列表的方式,特别适合根据已有序列生成新列表。

# 创建0到9的平方数列表
squares = [x**2 for x in range(10)]
print("平方数列表:", squares)  # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 创建偶数列表(0-20)
even_numbers = [x for x in range(21) if x % 2 == 0]
print("偶数列表:", even_numbers)

# 将字符串列表中的每个字符串转换为大写
fruits = ["apple", "banana", "orange"]
upper_fruits = [fruit.upper() for fruit in fruits]
print("大写水果名:", upper_fruits)  # 输出: ['APPLE', 'BANANA', 'ORANGE']

2.4. 使用*操作符重复元素

可以使用乘法运算符创建包含重复元素的列表。

# 创建包含3个"Hello"的列表
hello_list = ["Hello"] * 3
print("重复列表:", hello_list)  # 输出: ['Hello', 'Hello', 'Hello']

# 创建包含5个0的列表
zeros = [0] * 5
print("零列表:", zeros)  # 输出: [0, 0, 0, 0, 0]

# 注意:当元素为可变类型时需谨慎
nested = [[]] * 3  # 创建包含3个相同引用的空列表
nested[0].append(1)  # 修改第一个列表会影响所有列表
print("嵌套列表问题:", nested)  # 输出: [[1], [1], [1]]

3. 访问列表元素

3.1. 索引访问

列表中的每个元素都有一个唯一索引,从0开始。Python支持正向索引(0,1,2...)和反向索引(-1,-2,-3...)。

fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# 正向索引访问
print("第一个水果:", fruits[0])   # 输出: apple
print("第三个水果:", fruits[2])   # 输出: cherry

# 反向索引访问
print("最后一个水果:", fruits[-1])  # 输出: elderberry
print("倒数第二个水果:", fruits[-2]) # 输出: date

# 尝试访问不存在的索引会引发错误
try:
    print(fruits[5])  # 列表索引从0到4
except IndexError as e:
    print("错误:", e)  # 输出: list index out of range

3.2. 切片操作

切片可以访问列表的子集,语法为list[start:stop:step]

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 基本切片:从索引1到3(不包括4)
sub1 = numbers[1:4]
print("切片1:", sub1)  # 输出: [1, 2, 3]

# 省略start:从开始到索引3(不包括3)
sub2 = numbers[:3]
print("切片2:", sub2)  # 输出: [0, 1, 2]

# 省略stop:从索引2到结束
sub3 = numbers[2:]
print("切片3:", sub3)  # 输出: [2, 3, 4, 5, 6, 7, 8, 9]

# 带步长的切片:从0到9,步长为2
sub4 = numbers[::2]
print("步长切片:", sub4)  # 输出: [0, 2, 4, 6, 8]

# 反向切片:从9到0,步长为-1
sub5 = numbers[::-1]
print("反向切片:", sub5)  # 输出: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

# 复制整个列表
copy_list = numbers[:]
print("列表副本:", copy_list)

3.3. 遍历列表

使用循环可以遍历列表中的所有元素。

fruits = ["apple", "banana", "cherry"]

# 使用for循环遍历
print("方法1:直接遍历元素")
for fruit in fruits:
    print(fruit, end=" ")  # 输出: apple banana cherry

print("\n方法2:使用索引遍历")
for i in range(len(fruits)):
    print(f"索引{i}: {fruits[i]}")
    # 输出:
    # 索引0: apple
    # 索引1: banana
    # 索引2: cherry

print("方法3:使用enumerate获取索引和元素")
for index, fruit in enumerate(fruits):
    print(f"位置{index}: {fruit}")
    # 输出:
    # 位置0: apple
    # 位置1: banana
    # 位置2: cherry

4. 修改列表

4.1. 修改单个元素

通过索引可以直接修改列表中的元素。

colors = ["red", "green", "blue", "yellow"]
print("原始列表:", colors)

# 修改索引1处的元素
colors[1] = "emerald"
print("修改后:", colors)  # 输出: ['red', 'emerald', 'blue', 'yellow']

# 修改最后一个元素
colors[-1] = "gold"
print("修改最后元素:", colors)  # 输出: ['red', 'emerald', 'blue', 'gold']

# 尝试修改不存在的索引会引发错误
try:
    colors[4] = "purple"
except IndexError as e:
    print("错误:", e)  # 输出: list assignment index out of range

4.2. 切片修改

可以通过切片修改列表的多个元素。

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("原始列表:", numbers)

# 修改索引2到4处的元素(不包括5)
numbers[2:5] = [20, 30, 40]
print("切片修改后:", numbers)  # 输出: [0, 1, 20, 30, 40, 5, 6, 7, 8, 9]

# 替换多个元素为单个元素
numbers[3:6] = [99]
print("替换多个元素:", numbers)  # 输出: [0, 1, 20, 99, 6, 7, 8, 9]

# 删除切片中的元素(通过替换为空列表)
numbers[4:6] = []
print("删除切片元素:", numbers)  # 输出: [0, 1, 20, 99, 7, 8, 9]

4.3. 使用方法修改元素

列表提供了多种方法用于修改元素内容。

fruits = ["apple", "banana", "cherry"]
print("原始列表:", fruits)

# 使用append()在末尾添加元素
fruits.append("date")
print("添加后:", fruits)  # 输出: ['apple', 'banana', 'cherry', 'date']

# 使用insert()在指定位置插入元素
fruits.insert(1, "blueberry")  # 在索引1处插入
print("插入后:", fruits)  # 输出: ['apple', 'blueberry', 'banana', 'cherry', 'date']

# 使用extend()扩展列表(添加多个元素)
fruits.extend(["elderberry", "fig"])
print("扩展后:", fruits)  # 输出: ['apple', 'blueberry', 'banana', 'cherry', 'date', 'elderberry', 'fig']

5. 添加元素

5.1. append()方法

append()方法在列表末尾添加单个元素,这是最常用的添加方式。

tasks = ["学习Python", "写代码"]
print("初始任务列表:", tasks)

# 添加单个任务
tasks.append("调试程序")
print("添加后:", tasks)  # 输出: ['学习Python', '写代码', '调试程序']

# 可以添加任意类型元素
tasks.append(2023)  # 添加数字
print("添加数字后:", tasks)  # 输出: ['学习Python', '写代码', '调试程序', 2023]

# 添加另一个列表作为嵌套元素
tasks.append(["睡觉", "吃饭"])
print("添加嵌套列表后:", tasks)
# 输出: ['学习Python', '写代码', '调试程序', 2023, ['睡觉', '吃饭']]

5.2. insert()方法

insert()方法在指定位置插入单个元素,语法为insert(index, element)

colors = ["red", "green", "blue"]
print("原始颜色:", colors)

# 在索引0处插入(成为第一个元素)
colors.insert(0, "yellow")
print("开头插入:", colors)  # 输出: ['yellow', 'red', 'green', 'blue']

# 在索引2处插入
colors.insert(2, "purple")
print("中间插入:", colors)  # 输出: ['yellow', 'red', 'purple', 'green', 'blue']

# 在末尾插入(等价于append)
colors.insert(len(colors), "orange")
print("末尾插入:", colors)  # 输出: ['yellow', 'red', 'purple', 'green', 'blue', 'orange']

# 插入超出范围的索引会在末尾添加
colors.insert(99, "pink")
print("超出范围插入:", colors)
# 输出: ['yellow', 'red', 'purple', 'green', 'blue', 'orange', 'pink']

5.3. extend()方法

extend()方法用于将另一个可迭代对象的所有元素添加到当前列表的末尾。

numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
print("原始列表1:", numbers1)
print("原始列表2:", numbers2)

# 扩展numbers1,添加numbers2的元素
numbers1.extend(numbers2)
print("扩展后:", numbers1)  # 输出: [1, 2, 3, 4, 5, 6]

# 可以扩展其他可迭代对象(如字符串、元组)
letters = ["a", "b"]
letters.extend("cd")  # 字符串视为字符序列
print("扩展字符串后:", letters)  # 输出: ['a', 'b', 'c', 'd']

letters.extend((7, 8))  # 元组
print("扩展元组后:", letters)  # 输出: ['a', 'b', 'c', 'd', 7, 8]

# 注意:extend()与append()的区别
list1 = [1, 2, 3]
list2 = [4, 5, 6]

list1.append(list2)  # 将list2作为单个元素添加
print("append结果:", list1)  # 输出: [1, 2, 3, [4, 5, 6]]

list1 = [1, 2, 3]
list1.extend(list2)  # 将list2的元素逐个添加
print("extend结果:", list1)  # 输出: [1, 2, 3, 4, 5, 6]

5.4. 使用+操作符拼接

+操作符可以创建一个新列表,包含两个列表的所有元素。

list_a = [1, 2, 3]
list_b = [4, 5, 6]

# 使用+拼接
combined = list_a + list_b
print("拼接结果:", combined)  # 输出: [1, 2, 3, 4, 5, 6]

# 可以拼接多个列表
list_c = [7, 8, 9]
big_list = list_a + list_b + list_c
print("多列表拼接:", big_list)  # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 注意:+操作符会创建新列表,原列表不变
print("原列表A:", list_a)  # 输出: [1, 2, 3]
print("原列表B:", list_b)  # 输出: [4, 5, 6]

# +=操作符会修改原列表
list_a += list_b
print("+=后A:", list_a)  # 输出: [1, 2, 3, 4, 5, 6]
print("+=后B:", list_b)  # 输出: [4, 5, 6] (B不变)

6. 删除元素

6.1. del语句

del语句可以删除列表中的单个元素或切片。

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("原始列表:", numbers)

# 删除单个元素(索引2)
del numbers[2]
print("删除索引2后:", numbers)  # 输出: [0, 1, 3, 4, 5, 6, 7, 8, 9]

# 删除切片(索引3到5)
del numbers[3:6]
print("删除切片后:", numbers)  # 输出: [0, 1, 3, 7, 8, 9]

# 删除整个列表
del numbers
try:
    print(numbers)
except NameError as e:
    print("错误:", e)  # 输出: name 'numbers' is not defined

6.2. pop()方法

pop()方法移除并返回指定索引处的元素,默认移除最后一个元素。

stack = ["a", "b", "c", "d"]
print("原始栈:", stack)

# 弹出最后一个元素(无参数)
last = stack.pop()
print("弹出元素:", last)  # 输出: d
print("弹出后栈:", stack)  # 输出: ['a', 'b', 'c']

# 弹出指定索引处的元素
first = stack.pop(0)
print("弹出第一个元素:", first)  # 输出: a
print("弹出后栈:", stack)  # 输出: ['b', 'c']

# 尝试弹出空列表会引发错误
empty_list = []
try:
    empty_list.pop()
except IndexError as e:
    print("错误:", e)  # 输出: pop from empty list

6.3. remove()方法

remove()方法移除列表中第一个匹配的指定值,不返回任何值。

colors = ["red", "green", "blue", "red", "yellow"]
print("原始颜色列表:", colors)

# 移除第一个"red"
colors.remove("red")
print("移除第一个red后:", colors)  # 输出: ['green', 'blue', 'red', 'yellow']

# 尝试移除不存在的值会引发错误
try:
    colors.remove("purple")
except ValueError as e:
    print("错误:", e)  # 输出: list.remove(x): x not in list

# 检查元素是否存在再移除
if "green" in colors:
    colors.remove("green")
    print("移除green后:", colors)  # 输出: ['blue', 'red', 'yellow']

6.4. clear()方法

clear()方法移除列表中的所有元素,使其变为空列表。

data = [1, 2, 3, 4, 5]
print("原始数据:", data)

# 清空列表
data.clear()
print("清空后:", data)  # 输出: []

# 等价于 del data[:]
data2 = [10, 20, 30]
del data2[:]
print("del切片清空:", data2)  # 输出: []

7. 列表的其他常用方法

7.1. sort()与sorted()

sort()方法对列表进行原地排序,sorted()函数则返回排序后的新列表。

numbers = [5, 2, 8, 1, 9, 3]
print("原始数字:", numbers)

# 使用sort()原地排序(升序)
numbers.sort()
print("sort()升序:", numbers)  # 输出: [1, 2, 3, 5, 8, 9]

# 降序排序
numbers.sort(reverse=True)
print("sort()降序:", numbers)  # 输出: [9, 8, 5, 3, 2, 1]

# 使用sorted()函数(不改变原列表)
fruits = ["banana", "apple", "cherry", "date"]
sorted_fruits = sorted(fruits)
print("原水果列表:", fruits)  # 输出: ['banana', 'apple', 'cherry', 'date']
print("sorted()结果:", sorted_fruits)  # 输出: ['apple', 'banana', 'cherry', 'date']

# 降序排序
sorted_desc = sorted(fruits, reverse=True)
print("sorted()降序:", sorted_desc)  # 输出: ['date', 'cherry', 'banana', 'apple']

# 按字符串长度排序
len_sort = sorted(fruits, key=len)
print("按长度排序:", len_sort)  # 输出: ['date', 'apple', 'banana', 'cherry']

7.2. reverse()方法

reverse()方法原地反转列表元素的顺序。

data = [1, 2, 3, 4, 5]
print("原始数据:", data)

# 反转列表
data.reverse()
print("reverse()后:", data)  # 输出: [5, 4, 3, 2, 1]

# 使用切片实现相同效果(创建新列表)
reversed_data = data[::-1]
print("切片反转:", reversed_data)  # 输出: [1, 2, 3, 4, 5]
print("原数据不变:", data)  # 输出: [5, 4, 3, 2, 1]

7.3. count()方法

count()方法返回列表中指定值的出现次数。

letters = ["a", "b", "c", "a", "b", "a", "d"]
print("字母列表:", letters)

# 统计"a"的出现次数
a_count = letters.count("a")
print("'a'出现次数:", a_count)  # 输出: 3

# 统计"b"的出现次数
b_count = letters.count("b")
print("'b'出现次数:", b_count)  # 输出: 2

# 统计不存在的元素
e_count = letters.count("e")
print("'e'出现次数:", e_count)  # 输出: 0

# 统计列表元素中的子元素
nested = [[1, 2], [3, 4], [1, 2]]
count_nested = nested.count([1, 2])
print("嵌套列表[1,2]出现次数:", count_nested)  # 输出: 2

7.4. index()方法

index()方法返回指定值第一次出现的索引。

fruits = ["apple", "banana", "cherry", "apple", "date"]
print("水果列表:", fruits)

# 查找"cherry"的索引
cherry_idx = fruits.index("cherry")
print("'cherry'的索引:", cherry_idx)  # 输出: 2

# 查找第二个"apple"的索引(在指定范围内)
# 搜索从索引3开始到末尾
second_apple = fruits.index("apple", 3)  # 从索引3开始查找
print("第二个'apple'的索引:", second_apple)  # 输出: 3

# 尝试查找不存在的值
try:
    fruits.index("orange")
except ValueError as e:
    print("错误:", e)  # 输出: 'orange' is not in list

7.5. copy()方法

copy()方法创建列表的浅拷贝(与切片[:]效果相同)。

original = [1, 2, 3, [4, 5]]
print("原始列表:", original)

# 使用copy()创建副本
shallow_copy = original.copy()
print("浅拷贝:", shallow_copy)

# 修改副本中的不可变元素
shallow_copy[0] = 99
print("修改副本后:", shallow_copy)  # 输出: [99, 2, 3, [4, 5]]
print("原列表不变:", original)      # 输出: [1, 2, 3, [4, 5]]

# 修改副本中的可变元素(子列表)
shallow_copy[3][0] = 999
print("修改子列表后:", shallow_copy)  # 输出: [99, 2, 3, [999, 5]]
print("原列表也被修改:", original)     # 输出: [1, 2, 3, [999, 5]]

8. 列表推导式

列表推导式是一种简洁创建列表的方法,基本语法为[expression for item in iterable]

8.1. 基本列表推导式

# 创建1到10的平方数列表
squares = [x**2 for x in range(1, 11)]
print("平方数列表:", squares)  # 输出: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 创建字符串长度列表
fruits = ["apple", "banana", "cherry"]
lengths = [len(fruit) for fruit in fruits]
print("水果长度列表:", lengths)  # 输出: [5, 6, 6]

# 转换为大写字母列表
upper_letters = [char.upper() for char in "python"]
print("大写字母列表:", upper_letters)  # 输出: ['P', 'Y', 'T', 'H', 'O', 'N']

8.2. 带条件的列表推导式

可以在推导式后添加if条件进行过滤。

# 创建1到20中的偶数列表
evens = [x for x in range(1, 21) if x % 2 == 0]
print("偶数列表:", evens)  # 输出: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

# 创建长度大于5的水果名列表
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
long_fruits = [fruit for fruit in fruits if len(fruit) > 5]
print("长水果名列表:", long_fruits)  # 输出: ['banana', 'cherry', 'elderberry']

# 同时使用条件和表达式转换
# 将偶数乘以10,奇数保持原样
numbers = [1, 2, 3, 4, 5]
transformed = [x*10 if x % 2 == 0 else x for x in numbers]
print("转换后:", transformed)  # 输出: [1, 20, 3, 40, 5]

8.3. 多重循环的列表推导式

可以使用多个for循环生成嵌套结构的列表。

# 创建所有颜色和尺寸的组合
colors = ["red", "green", "blue"]
sizes = ["S", "M", "L"]
combinations = [f"{color}-{size}" for color in colors for size in sizes]
print("颜色尺寸组合:", combinations)
# 输出: ['red-S', 'red-M', 'red-L', 'green-S', 'green-M', 'green-L', 'blue-S', 'blue-M', 'blue-L']

# 创建3x3矩阵
matrix = [[row * 3 + col for col in range(3)] for row in range(3)]
print("3x3矩阵:")
for row in matrix:
    print(row)
# 输出:
# [0, 1, 2]
# [3, 4, 5]
# [6, 7, 8]

8.4. 嵌套列表的扁平化

# 扁平化嵌套列表
nested = [[1, 2, 3], [4, 5], [6], [7, 8, 9]]
flat = [element for sublist in nested for element in sublist]
print("扁平化后:", flat)  # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 只扁平化两层嵌套
deep_nested = [[1, [2, 3]], [4, 5], [6, [7, 8, 9]]]
flat_two = [x for sublist in deep_nested for x in (sublist if isinstance(sublist, list) else [sublist])]
print("两层扁平化:", flat_two)  # 输出: [1, [2, 3], 4, 5, 6, [7, 8, 9]]

9. 列表的复制

9.1. 浅复制

浅复制只复制最外层的容器,内部对象仍然是共享引用。创建浅复制的方法有:

使用copy()方法

使用切片[:]

使用list()构造函数

使用copy模块的copy()函数

import copy

original = [1, 2, 3, [4, 5, 6]]
print("原始列表:", original)

# 方法1:copy()方法
shallow_copy1 = original.copy()

# 方法2:切片
shallow_copy2 = original[:]

# 方法3:list()构造函数
shallow_copy3 = list(original)

# 方法4:copy.copy()
shallow_copy4 = copy.copy(original)

print("浅复制列表1:", shallow_copy1)
print("浅复制列表2:", shallow_copy2)
print("浅复制列表3:", shallow_copy3)
print("浅复制列表4:", shallow_copy4)

# 修改原始列表中的子元素
original[3][0] = 999
print("修改子元素后的原始列表:", original)  # 输出: [1, 2, 3, [999, 5, 6]]

# 所有浅复制列表的子元素都被修改
print("浅复制1:", shallow_copy1)  # 输出: [1, 2, 3, [999, 5, 6]]
print("浅复制2:", shallow_copy2)  # 输出: [1, 2, 3, [999, 5, 6]]
print("浅复制3:", shallow_copy3)  # 输出: [1, 2, 3, [999, 5, 6]]
print("浅复制4:", shallow_copy4)  # 输出: [1, 2, 3, [999, 5, 6]]

9.2. 深复制

深复制会递归复制所有嵌套对象,创建完全独立的副本。使用copy模块的deepcopy()函数。

import copy

original = [1, 2, 3, [4, 5, 6]]
print("原始列表:", original)

# 创建深拷贝
deep_copy = copy.deepcopy(original)

# 修改原始列表中的子元素
original[3][0] = 999
print("修改子元素后的原始列表:", original)  # 输出: [1, 2, 3, [999, 5, 6]]
print("深拷贝列表:", deep_copy)             # 输出: [1, 2, 3, [4, 5, 6]]

# 深拷贝列表不受原始列表修改的影响

9.3. 复制嵌套结构的注意事项

# 包含循环引用的列表(一个列表包含自身)
circular = [1, 2, 3]
circular.append(circular)
print("循环引用列表:", circular)  # 输出: [1, 2, 3, [...]]

# 尝试深拷贝循环引用
import copy
try:
    deep_circular = copy.deepcopy(circular)
    print("深拷贝循环引用成功")
except RecursionError as e:
    print("错误:", e)  # Python可以处理循环引用的深拷贝

# 包含可变对象的深拷贝
original = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(original)

original[0][0] = 99
print("原始列表:", original)  # 输出: [[99, 2], [3, 4]]
print("深拷贝列表:", deep_copy)  # 输出: [[1, 2], [3, 4]]

10. 列表作为堆栈和队列

10.1. 列表作为堆栈

堆栈是后进先出(LIFO)的数据结构,可以使用列表的append()pop()方法实现。

stack = []
print("空堆栈:", stack)

# 压入元素(入栈)
stack.append("first")
stack.append("second")
stack.append("third")
print("压入三个元素后:", stack)  # 输出: ['first', 'second', 'third']

# 弹出元素(出栈)
top = stack.pop()
print("弹出元素:", top)  # 输出: third
print("弹出后堆栈:", stack)  # 输出: ['first', 'second']

# 查看栈顶元素(不弹出)
if stack:
    print("栈顶元素:", stack[-1])  # 输出: second

# 检查堆栈是否为空
if not stack:
    print("堆栈为空")
else:
    print("堆栈不为空,元素数量:", len(stack))  # 输出: 堆栈不为空,元素数量: 2

# 清空堆栈
while stack:
    stack.pop()
print("清空后堆栈:", stack)  # 输出: []

10.2. 列表作为队列

队列是先进先出(FIFO)的数据结构。虽然可以用列表实现,但效率较低(因为从列表头部弹出元素需要移动所有元素),建议使用collections.deque

发表回复

后才能评论