Python推导式数据处理方式

2022-07-12 13:52:38
目录
前言1、列表推导式2、元组推导式3、集合推导式4、字典推导式

前言

推导式是一种独特的数据处理方式,可以快速的从一个数据序列构建另一个新的数据序列的结构体。常用的推导式有一下四种:

    列表推导式元组推导式集合推导式字典推导式

    1、列表推导式

    # coding:utf-8
    # Author:Yang Xiaopeng
    
    """
    语法格式
    [表达式 for 变量 in 变量]
    [表达式 for 变量 in 变量 if 条件表达式]
    上述格式中 的 表达式中的变量与for变量一致
    """
    old_list = [1, 2, 3, 4, 5]
    new_list = [new_list * new_list for new_list in old_list] # yes [1, 4, 9, 16, 25]
    # new_list = [new_list1 * new_list for new_list in old_list] # NameError: name 'new_list1' is not defined
    # new_list = [new_list * new_list for new_list2 in old_list] # NameError: name 'new_list' is not defined
    old_list = [old_list * old_list for old_list in old_list] # yes [1, 4, 9, 16, 25]
    print(old_list)
    print(new_list)
    new_list = [old_list for old_list in old_list if old_list%2 == 1] # yes [1, 9, 25]
    print(new_list)

    2、元组推导式

    # coding:utf-8
    # Author:Yang Xiaopeng
    
    """
    语法格式
    (表达式 for 变量 in 变量)
    (表达式 for 变量 in 变量 if 条件表达式)
    上述格式中 的 表达式中的变量与for变量一致
    """
    old_list = (1, 2, 3, 4, 5)
    new_list = (new_list * new_list for new_list in old_list) # yes 1_4_9_16_25_
    # new_list = [new_list1 * new_list for new_list in old_list] # NameError: name 'new_list1' is not defined
    # new_list = [new_list * new_list for new_list2 in old_list] # NameError: name 'new_list' is not defined
    old_list = (old_list * old_list for old_list in old_list) # yes 1_4_9_16_25_
    for item in new_list:
    print(item, end="_")
    print("")
    for item in old_list:
    print(item, end="_")
    print("")

    3、集合推导式

    # coding:utf-8
    # Time:2022/6/28 20:57
    # Author:Yang Xiaopeng
    """
    语法格式
    {表达式 for 变量 in 变量}
    {表达式 for 变量 in 变量 if 条件表达式}
    上述格式中 的 表达式中的变量与for变量一致
    """
    old_list = {1, 2, 3, 4, 5}
    new_list = {new_list * new_list for new_list in old_list} # yes {1, 4, 9, 16, 25}
    # new_list = {new_list1 * new_list for new_list in old_list} # NameError: name 'new_list1' is not defined
    # new_list = {new_list * new_list for new_list2 in old_list} # NameError: name 'new_list' is not defined
    old_list = {old_list * old_list for old_list in old_list} # yes {1, 4, 9, 16, 25}
    print(old_list)
    print(new_list)
    new_list = {old_list for old_list in old_list if old_list % 2 == 1} # yes {1, 9, 25}
    print(new_list)

    4、字典推导式

    # coding:utf-8
    # Author:Yang Xiaopeng
    """
    语法格式
    {key : value for key in 变量}
    {key : value for key in 变量 if 表达式}
    """
    old_dict = ["Zhang", "Wang", "Yang", "Jim"]
    new_dict = {key:len(key) for key in old_dict} # yes {1, 4, 9, 16, 25}
    print(old_dict)
    print(new_dict)
    new_dict = {lll:len(lll) for lll in old_dict if len(lll) % 2 == 0} # yes {1, 9, 25}
    print(new_dict)

    到此这篇关于Python推导式数据处理方式的文章就介绍到这了,更多相关Python推导式内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!