Python列表推导式教程 - 基础入门与示例
- Python
- 2025-08-03
- 1788
Python列表推导式教程
高效创建列表的Pythonic方法
什么是列表推导式?
列表推导式(List Comprehension)是Python中一种简洁高效的创建列表的方法。它可以用一行代码替代多行循环语句,使代码更简洁易读。
列表推导式的优势:
- 代码更简洁、更Pythonic
- 执行效率通常比普通循环更高
- 可读性强,逻辑表达清晰
- 减少临时变量使用
基础语法
列表推导式的基本结构:
[expression for item in iterable]
这等同于:
result = [] for item in iterable: result.append(expression)
简单示例
示例1:创建平方数列表
使用普通循环:
squares = [] for x in range(10): squares.append(x**2)
使用列表推导式:
squares = [x**2 for x in range(10)]
输出:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
示例2:转换字符串列表
words = ['hello', 'world', 'python'] upper_words = [word.upper() for word in words]
输出:['HELLO', 'WORLD', 'PYTHON']
带条件的列表推导式
语法:[expression for item in iterable if condition]
示例3:筛选偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = [x for x in numbers if x % 2 == 0]
输出:[2, 4, 6, 8, 10]
示例4:筛选以特定字母开头的单词
words = ['apple', 'banana', 'avocado', 'cherry', 'apricot'] a_words = [word for word in words if word.startswith('a')]
输出:['apple', 'avocado', 'apricot']
复杂表达式
示例5:带if-else的列表推导式
语法:[expression1 if condition else expression2 for item in iterable]
numbers = [1, 2, 3, 4, 5, 6] result = ['even' if x % 2 == 0 else 'odd' for x in numbers]
输出:['odd', 'even', 'odd', 'even', 'odd', 'even']
示例6:嵌套循环
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flattened = [num for row in matrix for num in row]
输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
使用技巧与注意事项
技巧1:处理多个列表
list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] combined = [(x, y) for x in list1 for y in list2]
输出:[(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')]
注意事项:避免过度复杂
虽然列表推导式很强大,但过度使用会使代码难以理解。如果推导式变得太长或太复杂,考虑使用传统的for循环。
不推荐写法:
# 过于复杂的推导式 result = [[x*y for y in range(10) if y % 2 == 0] for x in range(5) if x > 0]
总结
列表推导式是Python中强大且高效的工具,它可以帮助您:
- 简化列表创建过程
- 提高代码可读性
- 提升代码执行效率
- 减少代码行数
掌握列表推导式将使您的Python代码更加Pythonic!
本文由ShaoYiTai于2025-08-03发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://521pj.cn/20257216.html
发表评论