生成式的概念:列表、字典、集合用一个表达式创建一个有规律的序列,好处是简化代码。
1.列表生成式
1.案例一:创建一个列表,;列表内的数据为0-9。
# list1=[]
# i=0
# while i<10:
# list1.append(i)
# i+=1
# print(list1)
# for i in range(10):
# list1.append(i)
# print(list1)
list1=[i for i in range(10)]
print(list1)
运行结果
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2.案例二:带有if条件的列表生成式,要求0-9之间的偶数列表。
# list1=[i for i in range(0,10,2)]
# print(list1)
list1=[i for i in range(10) if i % 2==0]
print(list1)
运行结果
[0, 2, 4, 6, 8]
3.多for循环生成式,列如要生成这样的数据[(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]。
list1=[(i,j) for i in range(1,3) for j in range(3)]
print(list1)
运行结果
[(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
2.字典生成式
1.案例一:创建一个字典,key:1-5,values:为1-5的平方。
dict1={key:key**2 for key in range(1,6) }
print(dict1)
运行结果
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
2.案例二:合并两个列表为一个字典。
list1=['name','age','gender']
list2=['tom',21,'man']
dict1={list1[i]:list2[i] for i in range(len(list1))}
print(dict1)
运行结果
{'name': 'tom', 'age': 21, 'gender': 'man'}
3.案例三:从字典中提取想要的数据。
dict1={'book1':100,'book2':200,'book3':110,'book4':600,'book5':700,'book6':800}
dict2={key:value for key,value in dict1.items() if value>500}
print(dict2)
运行结果
{'book4': 600, 'book5': 700, 'book6': 800}
3.集合生成式
1.案例一有一个列表list1=[1,2,3,4]要求生成一个集合集合里的数据都是列表中数据的平方。
list1=[1,2,3,4,5]
set1={i**2 for i in list1}
print(set1)
运行结果
{1, 4, 9, 16, 25}