python列表推导式&&字典推导式

2024-04-23 19:36:12 浏览数 (2)

内容笔记简单我就直接上代码了使用推导式和常规方法进行对比

列表推导式

代码语言:javascript复制
alist = []
for i in range(1,11):
    if i % 2 == 0:
        alist.append(i*i)
print(alist)

#列表推导式
blist = [i*i for i in range(1,11) if i % 2 == 0]
print(alist)

字典推导式

代码语言:javascript复制
z_name = ["a","b","c","d"]
z_num  = {}
for i in z_name:
    z_num[i] = 0
print(z_num)
#字典推导式
z_num2 = {i:0 for i in z_num}
print(z_num2)

0 人点赞