列表生成式和字典生成式
一、列表生成式
列表生成式是利用其他列表创建新列表,其中可以嵌套for或者if。比如要找到1~20之间的偶数,一般情况下可以这样操作:
alist = []
for i in range(1,21):
if i % 2 == 0:
alist.append(i)
print(alist)
显示结果为:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
这样写的话代码量还是非常多的,其实可以用列表推导式进行优化,如下:
#在1~20中把偶数挑选出来
blist = [i for i in range(1,21) if i % 2 == 0]
print(blist)
其结果为:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
二、字典生成式
字典生成式和列表生成式类似,比如:有10个学生,成绩在60-100之间,常规写法如下:
import random
adict = {}
for i in range(1,11):
adict.update({'student' + str(i): random.randint(60, 101)})
print(adict)
结果为:
{'student1': 85, 'student2': 62, 'student3': 99, 'student4': 74, 'student5': 73, 'student6': 96, 'student7': 101, 'student8': 71, 'student9': 86, 'student10': 69}
用字典生成式可以进一步优化:
import random
bdict = {'student' + str(i): random.randint(60, 101) for i in range(1,11)}
print(bdict)
结果为:
{'student1': 94, 'student2': 71, 'student3': 82, 'student4': 79, 'student5': 70, 'student6': 67, 'student7': 72, 'student8': 96, 'student9': 80, 'student10': 82}
若要筛选出成绩在80分以上的学生:
import random
bdict = {'student' + str(i): random.randint(60, 101) for i in range(1,11)}
cdict = {name:score for name,score in bdict.items() if score > 80}
print('全班学生的成绩分别为:{0}'.format(bdict))
print('成绩大于80分的学生有:{0}'.format(cdict))
结果为:
全班学生的成绩分别为:{'student1': 74, 'student2': 63, 'student3': 82, 'student4': 67, 'student5': 101, 'student6': 67, 'student7': 98, 'student8': 97, 'student9': 72, 'student10': 101}
成绩大于80分的学生有:{'student3': 82, 'student5': 101, 'student7': 98, 'student8': 97, 'student10': 101}
将字典中的key值和value值调换:
adict = {'student3': 82, 'student5': 101, 'student7': 98, 'student8': 97, 'student10': 101}
bdict = {v:k for k,v in adict.items()}
print(bdict)
结果为:
{82: 'student3', 101: 'student10', 98: 'student7', 97: 'student8'}
将字典中的key值改为大写:
adict = {'student3': 82, 'student5': 101, 'student7': 98, 'student8': 97, 'student10': 101}
bdict = {k.upper():v for k,v in adict.items()}
print(adict)
print(bdict)
结果为:
{'student3': 82, 'student5': 101, 'student7': 98, 'student8': 97, 'student10': 101}
{'STUDENT3': 82, 'STUDENT5': 101, 'STUDENT7': 98, 'STUDENT8': 97, 'STUDENT10': 101}