
1、列表推导式,在中括号中包含表达式。
old_list=[0,1,2,3,4] new_list=[] foriteminold_list: ifitem%2==0: new_list.append(item) print(new_list)
2、字典推导式,将[]改为{},组成元素包括key和value。
old_student_score_info={
"Jack":{
"chinese":87,
"math":92,
"english":78
},
"Tom":{
"chinese":92,
"math":100,
"english":89
}
}
new_student_score_info={}
forname,scoresinold_student_score_info.items():
ifscores["math"]==100:
new_student_score_info.setdefault(name,scores)
print(new_student_score_info)3、大括号{}的集合推导和使用,只有一个组成元素。
old_list=[0,0,0,1,2
new_set={itemforiteminold_list}
print(new_set)以上是python中的三种推导介绍,希望对大家有所帮助。更多Python学习指导:python基础教程
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。