深入理解 Python 列表推导式:从基础到高阶应用
# 基础列表推导式示例
numbers = [1, 2, 3, 4, 5]
squares = [num**2 for num in numbers]
print(squares) # 输出: [1, 4, 9, 16, 25]
# 使用条件语句的列表推导式示例
even_squares = [num**2 for num in numbers if num % 2 == 0]
print(even_squares) # 输出: [4, 16]
# 嵌套列表推导式示例
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 高阶列表推导式示例
from math import sqrt
primes = [2, 3, 5, 7, 11, 13, 17, 19]
perfect_numbers = [6, 28, 496, 8128]
numbers_with_sum_of_divisors = {num: sum(divisor for divisor in range(1, int(sqrt(num)) + 1) if num % divisor == 0) for num in numbers if num not in perfect_numbers}
print(numbers_with_sum_of_divisors)
# 输出: {5: 1, 7: 1, 13: 6, 17: 8, 19: 7, 23: 12, 29: 18, 31: 12, 37: 6, ...}
这个示例展示了列表推导式的基础用法、如何加入条件语句以及如何进行嵌套和高阶操作。这些操作可以用于快速生成列表,提高代码的简洁性和可读性。
评论已关闭