品易云推流 关闭
文章详情页
文章 > Python基础教程 > python中的三种推导式介绍

python中的三种推导式介绍

python推导式

头像

小妮浅浅

2021-10-18 10:22:084586浏览 · 0收藏 · 0评论

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

old_list = [0,1,2,3,4,5]
new_list = []
for item in old_list:
    if item % 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 = {}
for name, scores in old_student_score_info.items():
    if scores["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 = {item for item in old_list}
print(new_set)

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

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图