Python列表推导式(List Comprehensions)是一种简洁、高效的创建列表的方法。它可以用一行代码生成一个新的列表,而不需要使用循环或其他复杂的方法。列表推导式支持以下操作:
numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if num % 2 == 0] # 筛选出偶数
print(even_numbers) # 输出:[2, 4]
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num * num for num in numbers] # 计算平方值
print(squared_numbers) # 输出:[1, 4, 9, 16, 25]
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
combined_list = [item for sublist in [list1, list2] for item in sublist] # 合并两个列表
print(combined_list) # 输出:[1, 2, 3, 'a', 'b', 'c']
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys_list = [key for key in my_dict] # 提取字典的键
print(keys_list) # 输出:['a', 'b', 'c']
values_list = [value for value in my_dict.values()] # 提取字典的值
print(values_list) # 输出:[1, 2, 3]
nested_list = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in nested_list for item in sublist] # 展开嵌套列表
print(flat_list) # 输出:[1, 2, 3, 4, 5, 6]
总之,Python列表推导式是一种非常强大的工具,可以简化代码并提高开发效率。