热门IT资讯网

Python之字典生成式

发表于:2024-11-24 作者:热门IT资讯网编辑
编辑最后更新 2024年11月24日,字典生成式示例一、例如生成字典{'java': 89, 'python': 90, 'perl': 91}b = ['java','python','perl']s = [89,90,91]d = {

字典生成式示例


一、例如生成字典{'java': 89, 'python': 90, 'perl': 91}

b = ['java','python','perl']s = [89,90,91]d = {}# for in 循环for i,j in zip(b,s):    d[i] = jprint(d) #{'java': 89, 'python': 90, 'perl': 91}# 字典生成式d = {i:n for i,n in zip(b,s)}print(d) #{'java': 89, 'python': 90, 'perl': 91}


二、添加if判断

d = {}for i,n in zip(b,s):    if n >= 90:        d[i] = nprint(d) #{'python': 90, 'perl': 91}d = {i:n for i,n in zip(b,s) if n >=90 }print(d) #{'python': 90, 'perl': 91}


三、双重循环

d = {}#双重for in 循环for i in range(1,4):    for n in range(1,4):        d[i] = nprint(d) #{1: 3, 2: 3, 3: 3} 因为key唯一,后面的key:value都被1:3 2:3 3:3覆盖掉了# 字典生成式d = {i:n for i in range(1,4) for n in range(1,4)}print(d) # {1: 3, 2: 3, 3: 3}


四、双重循环,嵌套if

d = {}# 双重for in循环,嵌套iffor i in range(1,4):    for n in range(1,4):        if n < 3:           d.update([(i,n)])print(d) #{1: 2, 2: 2, 3: 2}# 字典生成式d = {i:n for i in range(1,4) for n in range(1,4) if n <3}print(d) #{1: 2, 2: 2, 3: 2}


0