前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【说站】python中的三种推导式介绍

【说站】python中的三种推导式介绍

作者头像
很酷的站长
发布2022-11-24 10:18:21
2510
发布2022-11-24 10:18:21
举报
文章被收录于专栏:站长的编程笔记

python中的三种推导式介绍

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

代码语言:javascript
复制
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。

代码语言:javascript
复制
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、集合推导式跟使用大括号{},组成元素也只要一个。

代码语言:javascript
复制
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电脑。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • python中的三种推导式介绍
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档