字数 2868,阅读大约需 15 分钟
列表(List)是Python中最基本、最常用的数据结构,用于存储有序的元素集合。

特点:
# 创建列表fruits = ["苹果", "香蕉", "橙子"]numbers = [1, 2, 3, 4, 5]mixed = [1, "hello", 3.14, True]empty = [] # 空列表print(fruits) # ['苹果', '香蕉', '橙子']# 方括号创建colors = ["红", "绿", "蓝"]# 空列表data = []# 包含不同类型的元素person = ["张三", 25, "北京", True]# 从字符串创建chars = list("Python")print(chars) # ['P', 'y', 't', 'h', 'o', 'n']# 从元组创建nums = list((1, 2, 3))print(nums) # [1, 2, 3]# 从 range 创建numbers = list(range(1, 6))print(numbers) # [1, 2, 3, 4, 5]# 生成 0-9 的列表zeros = [0] * 10print(zeros) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]# 生成 1-10 的平方squares = [x ** 2 for x in range(1, 11)]print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]# 只保留偶数evens = [x for x in range(20) if x % 2 == 0]print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]# 嵌套循环pairs = [(x, y) for x in range(3) for y in range(3)]print(pairs) # [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]# 转换数据类型str_nums = ["1", "2", "3", "4"]int_nums = [int(x) for x in str_nums]print(int_nums) # [1, 2, 3, 4]fruits = ["苹果", "香蕉", "橙子", "葡萄", "西瓜"]# 正向索引print(fruits[0]) # 苹果print(fruits[2]) # 橙子print(fruits[4]) # 西瓜# 负向索引(从后往前)print(fruits[-1]) # 西瓜(最后一个)print(fruits[-2]) # 葡萄(倒数第二个)print(fruits[-5]) # 苹果(倒数第五个,即第一个)# 修改元素fruits[1] = "芒果"print(fruits) # ['苹果', '芒果', '橙子', '葡萄', '西瓜']numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]# 基本切片 [start:end](不包括 end)print(numbers[2:5]) # [2, 3, 4]print(numbers[:4]) # [0, 1, 2, 3](从头开始)print(numbers[6:]) # [6, 7, 8, 9](到结尾)print(numbers[:]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9](复制整个列表)# 带步长 [start:end:step]print(numbers[::2]) # [0, 2, 4, 6, 8](每隔一个)print(numbers[1::2]) # [1, 3, 5, 7, 9](奇数位置)print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0](反转列表)print(numbers[1:8:2]) # [1, 3, 5, 7]# 负索引切片print(numbers[-3:]) # [7, 8, 9](最后三个)print(numbers[:-3]) # [0, 1, 2, 3, 4, 5, 6](除了最后三个)print(numbers[-1:-5:-1]) # [9, 8, 7, 6](反向取最后四个)fruits = ["苹果", "香蕉"]# append() - 添加到末尾fruits.append("橙子")print(fruits) # ['苹果', '香蕉', '橙子']# insert() - 插入到指定位置fruits.insert(1, "葡萄")print(fruits) # ['苹果', '葡萄', '香蕉', '橙子']# extend() - 扩展列表(添加多个元素)fruits.extend(["西瓜", "芒果"])print(fruits) # ['苹果', '葡萄', '香蕉', '橙子', '西瓜', '芒果']# + 运算符(创建新列表)more_fruits = fruits + ["草莓", "蓝莓"]print(more_fruits)# * 运算符(重复列表)doubled = [1, 2] * 3print(doubled) # [1, 2, 1, 2, 1, 2]fruits = ["苹果", "香蕉", "橙子", "香蕉", "葡萄"]# remove() - 删除第一个匹配的元素fruits.remove("香蕉")print(fruits) # ['苹果', '橙子', '香蕉', '葡萄']# pop() - 删除并返回指定位置的元素(默认最后一个)last = fruits.pop()print(last) # 葡萄print(fruits) # ['苹果', '橙子', '香蕉']second = fruits.pop(1)print(second) # 橙子print(fruits) # ['苹果', '香蕉']# del - 删除元素或切片del fruits[0]print(fruits) # ['香蕉']# clear() - 清空列表fruits.clear()print(fruits) # []numbers = [1, 2, 3, 4, 5]# 修改单个元素numbers[2] = 30print(numbers) # [1, 2, 30, 4, 5]# 修改多个元素(切片赋值)numbers[1:4] = [20, 30, 40]print(numbers) # [1, 20, 30, 40, 5]# 替换不同数量的元素numbers[1:3] = [100, 200, 300, 400]print(numbers) # [1, 100, 200, 300, 400, 5]fruits = ["苹果", "香蕉", "橙子", "葡萄"]# in 运算符print("香蕉" in fruits) # Trueprint("西瓜" in fruits) # False# index() - 查找元素的索引print(fruits.index("橙子")) # 2# print(fruits.index("西瓜")) # ValueError: not in list# count() - 统计元素出现次数items = [1, 2, 2, 3, 2, 4, 2]print(items.count(2)) # 4# len() - 获取列表长度print(len(fruits)) # 4numbers = [5, 2, 8, 1, 9, 3]# sort() - 原地排序(修改原列表)numbers.sort()print(numbers) # [1, 2, 3, 5, 8, 9]# 降序排序numbers.sort(reverse=True)print(numbers) # [9, 8, 5, 3, 2, 1]# sorted() - 返回新列表(不修改原列表)original = [5, 2, 8]sorted_list = sorted(original)print(sorted_list) # [2, 5, 8]print(original) # [5, 2, 8](未变)# reverse() - 反转列表fruits = ["苹果", "香蕉", "橙子"]fruits.reverse()print(fruits) # ['橙子', '香蕉', '苹果']# 自定义排序(按字符串长度)words = ["python", "is", "awesome", "a"]words.sort(key=len)print(words) # ['a', 'is', 'python', 'awesome']# ❌ 错误:只是引用,不是复制list1 = [1, 2, 3]list2 = list1list2.append(4)print(list1) # [1, 2, 3, 4](原列表也被修改了!)# ✅ 正确:浅拷贝list1 = [1, 2, 3]list2 = list1.copy()list2.append(4)print(list1) # [1, 2, 3]print(list2) # [1, 2, 3, 4]# 其他复制方式list2 = list(list1)list2 = list1[:]import copylist2 = copy.copy(list1)fruits = ["苹果", "香蕉", "橙子"]# 直接遍历元素for fruit in fruits: print(fruit)# 带索引遍历for i in range(len(fruits)): print(f"{i}: {fruits[i]}")# 优雅写法:enumerate()for index, fruit in enumerate(fruits): print(f"{index}: {fruit}")# 从 1 开始计数for index, fruit in enumerate(fruits, start=1): print(f"{index}. {fruit}")names = ["小明", "小红", "小刚"]scores = [85, 92, 78]# zip() 并行遍历for name, score in zip(names, scores): print(f"{name} 考了 {score} 分")# 带索引for index, (name, score) in enumerate(zip(names, scores), start=1): print(f"第{index}名:{name} - {score}分")todos = []while True: print("\n=== 待办事项 ===") print("1. 添加任务") print("2. 查看任务") print("3. 完成任务") print("4. 退出") choice = input("请选择操作:") if choice == "1": task = input("输入任务:") todos.append(task) print("✅ 任务已添加") elif choice == "2": if todos: for i, task in enumerate(todos, start=1): print(f"{i}. {task}") else: print("暂无任务") elif choice == "3": if todos: print("当前任务:") for i, task in enumerate(todos, start=1): print(f"{i}. {task}") num = int(input("完成第几个任务?")) removed = todos.pop(num - 1) print(f"✅ 已完成:{removed}") else: print("没有任务") elif choice == "4": print("再见!") breakscores = []print("=== 成绩统计 ===")print("输入成绩(输入 -1 结束):")while True: score = float(input("成绩:")) if score == -1: break scores.append(score)if scores: print(f"\n📊 统计结果:") print(f"人数:{len(scores)}") print(f"最高分:{max(scores)}") print(f"最低分:{min(scores)}") print(f"平均分:{sum(scores) / len(scores):.2f}") print(f"及格率:{len([s for s in scores if s >= 60]) / len(scores) * 100:.1f}%")else: print("没有输入成绩")# 方法 1:使用 setnumbers = [1, 2, 2, 3, 3, 3, 4, 4, 5]unique = list(set(numbers))print(unique) # [1, 2, 3, 4, 5](顺序可能改变)# 方法 2:保持原顺序numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5]unique = []for num in numbers: if num not in unique: unique.append(num)print(unique) # [1, 2, 3, 4, 5]# 方法 3:列表推导式numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5]unique = [][unique.append(x) for x in numbers if x not in unique]print(unique)cart = []products = [ {"name": "苹果", "price": 5}, {"name": "香蕉", "price": 3}, {"name": "橙子", "price": 4}, {"name": "葡萄", "price": 8},]print("=== 商品列表 ===")for i, product in enumerate(products, start=1): print(f"{i}. {product['name']} - ¥{product['price']}")while True: choice = input("\n选择商品编号(输入 q 结账):") if choice == 'q': break idx = int(choice) - 1 if 0 <= idx < len(products): cart.append(products[idx]) print(f"✅ 已添加 {products[idx]['name']}") else: print("无效选择")# 结算if cart: print("\n=== 购物车 ===") total = 0 for item in cart: print(f"{item['name']} - ¥{item['price']}") total += item['price'] print(f"\n总计:¥{total}")else: print("购物车为空")# 3x3 矩阵matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]print(matrix[0]) # [1, 2, 3]print(matrix[0][1]) # 2print(matrix[2][2]) # 9# 动态创建rows, cols = 3, 4grid = [[0] * cols for _ in range(rows)]print(grid) # [[0,0,0,0], [0,0,0,0], [0,0,0,0]]matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]# 嵌套循环for row in matrix: for cell in row: print(cell, end=" ") print()# 带索引for i, row in enumerate(matrix): for j, cell in enumerate(row): print(f"matrix[{i}][{j}] = {cell}")fruits = ["苹果", "香蕉", "橙子"]# ❌ 错误print(fruits[3]) # IndexError: list index out of range# ✅ 正确:先检查if len(fruits) > 3: print(fruits[3])# 或用 try-excepttry: print(fruits[3])except IndexError: print("索引超出范围")numbers = [1, 2, 3, 4, 5]# ❌ 可能出问题for num in numbers: if num % 2 == 0: numbers.remove(num)# ✅ 正确:创建新列表numbers = [num for num in numbers if num % 2 != 0]# 或倒序遍历numbers = [1, 2, 3, 4, 5]for i in range(len(numbers) - 1, -1, -1): if numbers[i] % 2 == 0: numbers.pop(i)# ❌ 浅拷贝问题list1 = [[1, 2], [3, 4]]list2 = list1.copy()list2[0][0] = 999print(list1) # [[999, 2], [3, 4]](原列表也被修改!)# ✅ 深拷贝import copylist2 = copy.deepcopy(list1)生成杨辉三角的前 10 行:
1 1 1 1 2 1 1 3 3 11 4 6 4 1...提示:每行首尾是 1,中间元素 = 上一行相邻两元素之和
输入一段英文文本,统计每个单词出现的次数,按频率排序输出。
示例:
输入:hello world hello python world hello输出:hello: 3world: 2python: 1用二维列表实现井字棋(Tic-Tac-Toe):
列表核心操作速查表:
[]list() | ||
list[index] | ||
list[start:end:step] | ||
append()insert(), extend() | ||
remove()pop(), del, clear() | ||
list[index] = value | ||
inindex(), count() | ||
sort()sorted() | ||
reverse()[::-1] | ||
copy()[:], list() | ||
len() | ||
sum() | ||
max()min() |
关键要点:
sort() 修改原列表,sorted() 返回新列表Note
[1] 列表类型: https://docs.python.org/zh-cn/3/library/stdtypes.html#lists[2] 列表推导式: https://docs.python.org/zh-cn/3/tutorial/datastructures.html#list-comprehensions[3] 列表操作的时间复杂度: https://wiki.python.org/moin/TimeComplexity