字典生成式示例
一、例如生成字典{'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] = j print(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] = n print(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] = n print(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循环,嵌套if for 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}