• 技术文章 >Python技术 >Python基础教程

    python中的三种推导式介绍

    小妮浅浅小妮浅浅2021-10-18 10:22:08原创4227

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

    1

    2

    3

    4

    5

    6

    7

    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。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

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

    1

    2

    3

    4

    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电脑。

    专题推荐:python推导式
    上一篇:如何用python画月饼 下一篇:python字符串翻转的方法

    相关文章推荐

    • python字符串的基础操作• python列表的基本用法• Python集合有什么特点• Python字典的特点• python uiautomator2的点击操作• python socket的连接步骤• python使用VS接收数据• python中echo服务器的介绍• python中requests如何优化接口调用• python快速排序算法的使用• python中PCA的处理过程

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网