列表推到式与字典推导式

a = [1,2,3,4,5,6,7,8]
b = [i**3 for i in a]
print(b)


c = [i**2 for i in a if i >=5]

# 同样,集合set和元祖都可以
a = (1,2,3,4,5)
d = (i **2 for i in a)

字典推导式

students = {
  '张三':18
  '李四':19
  '王五':20
}
#获取字典的键
s = [key for key,value in  students.items()]
#将字典k,v颠倒
s1 = {value:key for key,value in  students.items()}

# 元组返回的是generator ,因为元组是不可变的
s = (key for key,value in  students.items())

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