Python中的字典生成式

练习1: 假设有20个学生,学生名为westosX,学生成绩在60~100之间,
筛选出成绩在90分以上的学生

import random
stuInfo = {}
for i in range(20):
    name = 'westos' + str(i)
    score = random.randint(60,100)
    stuInfo[name] = score
print(stuInfo)
highscore = {}

#用for循环
for name,score in stuInfo.items():
    if score > 90:
        highscore[name] = score
print(highscore)

#用字典生成式
print({name: score for name,score in stuInfo.items() if score > 90})
结果:
{'westos0': 67, 'westos1': 84, 'westos2': 86, 'westos3': 77, 'westos4': 90, 'westos5': 93, 
'westos6': 80, 'westos7': 78, 'westos8': 69, 'westos9': 95, 'westos10': 63, 'westos11': 76, 
'westos12': 88, 'westos13': 63, 'westos14': 87, 'westos15': 81, 'westos16': 90, 'westos17': 72, 
'westos18': 84, 'westos19': 98}
{'westos5': 93, 'westos9': 95, 'westos19': 98}

练习2: 将所有key值变为大写

d = dict(a=1,b=2)
print(d)
new_d = {}
#用for循环
for i in d:
    new_d[i.upper()] = d[i]
print(new_d)
#用字典生成式
print({k.upper():v for k,v in d.items()})
结果:
{'a': 1, 'b': 2}
{'A': 1, 'B': 2}

练习3: 大小写、value值和并,统一以小写输出

d = dict(a=2,b=1,c=2,B=9,A=10)
new_d = {}
#循环
for k,v in d.items():
    low_k = k.lower()
    if low_k not in new_d:
        new_d[low_k] = v
    else:
        new_d[low_k] += v
print(new_d)
#字典生成式
print({k.lower():d.get(k.lower(),0) + d.get(k.upper(),0) for k in d})

猜你喜欢

转载自blog.csdn.net/qq_44224894/article/details/88917772
今日推荐