一、列表推导式与普通方法对比
# 例1:while循环创建list list0 = [] i = 0 while i < 10: list0.append(i) i += 1 print(list0) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 例2:for循环创建list list1 = [] for num in range(10): list1.append(num) print(list1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 例3.1:列表推导式创建list list2 = [i for i in range(10)] print(list2) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 例3.2:带if的列表推导式 list3 = [i for i in range(1, 10) if i % 2 == 0] print(list3) # [2, 4, 6, 8]
由上面可以看出:
代码代码量:while循环>for循环>推导式
推导式本质是for循环的化简
二、字典推导式
# 1、创建字典推导式 dict1 = {i: i**2 for i in range(1, 5)} print(dict1) # {1: 1, 2: 4, 3: 9, 4: 16} # 2、字典推导式合并数列为字典 list1 = ['name', 'age'] list2 = ['Tom', 20] dict2 = {list1[i]: list2[i] for i in range(len(list1))} print(dict2) # {'name': 'Tom', 'age': 20} # 3、字典推导式提取 dict3 = {'MBP': 220, 'hp': 123, 'dell': 125} count1 = {key: value for key, value in dict3.items() if value >= 200} print(count1) # {'MBP': 220}
三、集合推导式
set1 = {i**2 for i in range(3)} print(set1) # {0, 1, 4} list1 = [1, 1, 2] set2 = {i**2 for i in list1} print(set2) # {1, 4} 集合有去重功能