最简形式:[expression for item in list]
""" 求1-5 的平方 """ print([i ** 2 for i in range(1, 6)]) # 输出结果:[1, 4, 9, 16, 25]
word_list = ["I", "love", "China"] print([item.title() for item in word_list]) # 输出结果:['I', 'Love', "China"]
过滤条件形式 [expression for item in list if conditional]
如果只有if, 则if在for循环后边;如果有if...else, 则if...else在for循环前边
list_val = [] for i in range(1, 21): if i % 2 ==0: list_val.append(i) print(list_val) # 列表解析式 print([i for i in range(1, 21) if i % 2 == 0]) # 运行结果:[2, 4, 6, 8, 10, 12, 14, 16, 18]
names = ['Elsa', 'John', 'Jessie'] new_list = [] for item in names: if len(item) > 4: new_list.append(item.upper()) else: new_list.append(item.lower()) print(new_list) # 列表解析式 print([item.upper() if len(item) >4 else item.lower() for item in names]) # 运行结果:['elsa', 'john', 'JESSIE']
循环嵌套形式[expression for i in list1 for j in list2]
list_val = [] for i in range(1,3): for j in range(1,3): list_val.append(f'{i} + {j}') print(list_val) # 列表解析式 print([f'{i} + {j}' for i in range(1, 3) for j in range(1, 3)]) # 运行结果:['1 + 1', '1 + 2', '2 + 1', '2 + 2']