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列表推導式是一種非常強大的工具,可以簡化代碼并提高開發效率。