1. 列表推导式
⽤⼀个表达式创建⼀个有规律的列表或控制⼀个有规律列表。(从for循环优化而来)
# # 创建一个1-10的列表
# i = 1
# lt = []
# while i < 11 :
# lt.append(i)
# i += 1
# print(lt)
# lt = []
# for i in range(1,11) :
# lt.append(i)
# print(lt)
# 使用推导式
lt = [ i for i in range(1,11)]
print(lt)
# 需求:创建0-10的偶数列表
lt = [i for i in range(0,11,2)]
print(lt)
lt = [i for i in range(0,11) if i % 2 == 0]
print(lt)
"""
多for的列表推导式 <==> for循环嵌套
"""
# lt = []
# for i in range(1,3) :
# for j in range(3):
# lt.append((i,j))
# print(lt)
lt = [(i,j) for i in range(1,3) for j in range(3)]
print(lt)
2. 字典推导式
快速合并列表为字典或提取字典中⽬标数据
# 创建⼀个字典:字典key是1-5数字,value是这个数字的2次⽅。
dict1 = {i:i**2 for i in range(1,6)}
print(dict1)
# 何快速合并为⼀个字典
list1 = ['name', 'age', 'gender']
list2 = ['Tom', 20, 'man']
# dict2 = {}
# for index,key in enumerate(list1,start=0) :
# dict2[key] = list2[index]
# else:
# print("创建结束!")
# print(dict2)
dict2 = {i:j for i in list1 for j in list2}
# for i in range(len(list1)) :
# dict2[list1[i]] = list2[i]
# print(dict2)
dict3 = {list1[i]:list2[i] for i in range(len(list1))}
print(dict3)
dict4 = {key : list2[index] for index,key in enumerate(list1,start=0)}
print(dict4)
# 提取字典中⽬标数据
counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99}
# 提取上述电脑数量⼤于等于200的字典数据
dict5 = {k : v for k,v in counts.items() if v >= 200}
print(dict5)
3. 集合推导式
list1 = [1, 1, 2]
set1 = {i ** 2 for i in list1}
print(set1) # {1, 4}