13、列表推导式与字典推导式

# 从 1 到 10 所有偶数的平方

alist = []

for i in range(1,11):

    if(i %2 ==0):

        alist.append(i * i)

print(alist)

# python优雅的写法

blist = [i*i for i in range(1,11) if (i %2) ==0]

print(blist)


chinese_zodiac ='猴鸡狗猪鼠牛虎兔龙蛇马羊'

cz_num = {}

for i in chinese_zodiac:

    cz_num[i] =0

print(cz_num)

# python优雅的写法

dz_num = {i:0 for i in chinese_zodiac}

print(dz_num)

你可能感兴趣的:(13、列表推导式与字典推导式)