print({i **2for i in{1,2,3,3}})print({i **2for i in{1,2,3,9,12,9}if i %3==0})
运行结果:
{1,4,9}{81,9,144}
2、字典生成式
例1
"""
# _*_coding:utf-8 _*_
Name:字典生成式.py
Date:4/3/19
Author:LiMin-wsp
Connect:314690259@qq.com
Desc:
""""""
假设有20个学生,学生名为westosX,学生成绩在60~100之间,
筛选出成绩在90分以上的学生
""""""
普通方法:
t random
d = {}
for i in range(20):
name = 'westos' + str(i)
score = random.randint(60,100)
d[name] = score
# print(d)
li = {}
def fun_01():
for k,v in d.items():
if v > 90:
li[k]=v
print(li)
fun_01()
"""##字典生成式import random
d ={}for i inrange(20):
name ='westos'+str(i)
score = random.randint(60,100)
d[name]= score
print({k:v for k,v in d.items()if v >90})
运行结果:
{'westos0':96,'westos1':95,'westos9':97,'westos12':100,'westos13':99,'westos14':94,'westos16':98,'westos18':93}
例2
"""
# _*_coding:utf-8 _*_
Name:字典生成式_02.py
Date:4/3/19
Author:LiMin-wsp
Connect:314690259@qq.com
Desc:
""""""
将所有key值变为大写
""""""
普通方法:
d = dict(a=1,b=4)
print(d)
new_d = {}
for i in d:
new_d[i.upper()] = d[i]
print(new_d)
"""##字典生成式
d =dict(a=1,b=4)print({k.upper():v for k,v in d.items()})
运行结果:
{'A':1,'B':4}
例3:大小写、value值和并,统一以小写输出
"""
# _*_coding:utf-8 _*_
Name:字典生成_03.py
Date:4/3/19
Author:LiMin-wsp
Connect:314690259@qq.com
Desc:
""""""
大小写、value值和并,统一以小写输出
""""""
普通方法:
d = dict(a=2,b=1,c=2,B=9,A=10)
print(d)
new_d = {}
for k,v in d.items():
new_k = k.lower()
if new_k in new_d:
new_d[new_k] += v
else:
new_d[new_k] = v
print(new_d)
"""##字典生成式
d =dict(a=2,b=1,c=2,B=9,A=10)print(d)print({k.lower():d.get(k.lower(),0)+d.get(k.upper(),0)for k in d})
运行结果:
{'a':2,'b':1,'c':2,'B':9,'A':10}{'a':12,'b':10,'c':2}
1、集合生成式print({i ** 2 for i in {1,2,3,3}})print({i ** 2 for i in {1,2,3,9,12,9} if i % 3 == 0 })运行结果:{1, 4, 9}{81, 9, 144}2、字典生成式 例1"""# _*_coding:utf-8 _*_Name:字典生成式.pyDate:4/3/19Author...