python中的三种推导式介绍

1、列表推导式,在一个中括号里包含一个表达式。

old_list=[0,1,2,3,4,5]
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,3]

new_set={itemforiteminold_list}
print(new_set)

以上就是python中的三种推导式介绍,希望对大家有所帮助。更多Python学习指路:Python基础教程

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。