标签:name 需求 大于 count 语句 循环 大于等于 合并 等于
用一个表达式创建一个有规律的列表或控制一个有规律列表。
list = [i for i in range(10)] print(list) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
第一行代码中第一个i为返回值,后面的式子为不带循环体的for循环
list = [i for i in range(10) if i % 2 == 0] print(list) # [0, 2, 4, 6, 8]
if 实现对i的过滤
list = [(i, j) for i in range(1, 3) for j in range(3)] print(list) # [(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
相当于嵌套for循环
dist1 = {i: i**2 for i in range(1, 5)} print(dist1) # {1: 1, 2: 4, 3: 9, 4: 16}
list1 = [‘name‘, ‘age‘, ‘gender‘] list2 = [‘Tom‘, 20, ‘man‘] dict1 = {list1[i]: list2[i] for i in range(len(list1))} print(dict1) # {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘man‘}
counts = {‘MBP‘: 268, ‘HP‘: 125, ‘DELL‘: 201, ‘Lenovo‘: 199, ‘acer‘: 99} # 需求:提取上述电脑数量大于等于200的字典数据 count1 = {key: value for key,value in counts.items() if value > 200} print(count1) # {‘MBP‘: 268, ‘DELL‘: 201}
list1 = [1, 1, 2] set1 = {i ** 2 for i in list1} print(set1) # {1, 4}
1. 写推导式时,先写for语句和if语句,再写前面的返回值
标签:name 需求 大于 count 语句 循环 大于等于 合并 等于
原文地址:https://www.cnblogs.com/liuxuelin/p/14181567.html