• 列表推导式、字典推导式、集合推导式


    一、列表推导式

    例一:

    multiples = [i for i in range(30) if i % 3 is 0]
    print(multiples)
    # Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

    例二:

    def squared(x):
        return x*x
    multiples = [squared(i) for i in range(30) if i % 3 is 0]
    print multiples
    #  Output: [0, 9, 36, 81, 144, 225, 324, 441, 576, 729]

    2、使用()生成generator

    将俩表推导式的[]改成()即可得到生成器。

    multiples = (i for i in range(30) if i % 3 is 0)
    print(type(multiples))
    #  Output: <type 'generator'>

    二、字典推导式

    # 因为key是唯一的,所以最后value都是1
    dict_a = {key: value for key in 'python' for value in range(2)}
    print(dict_a)
    
    # 可以根据键来构造值
    dict_b = {key: key * key for key in range(6)}
    print(dict_b)
    
    # 遍历一个有键值关系的可迭代对象
    list_phone = [('HUAWEI', '华为'), ('MI', '小米'), ('OPPO', 'OPPO'), ('VIVO', 'VIVO')]
    dict_c = {key: value for key, value in list_phone}
    print(dict_c)
    
    
    {'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}
    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
    {'HUAWEI': '华为', 'MI': '小米', 'OPPO': 'OPPO', 'VIVO': 'VIVO'}

    三,集合推导式

    # 遍历一个可迭代对象生成集合
    set_a = {value for value in '有人云淡风轻,有人负重前行'}
    print(set_a)

    {'负', '前', '重', '有', '云', ',', '行', '风', '人', '淡', '轻'}
     
  • 相关阅读:
    洛谷P2602 [ZJOI2010]数字计数 题解
    数位DP模板
    The Meaningless Game 思维题
    CF55D Beautiful numbers 数位DP
    NOIP 2016 洛谷 P2827 蚯蚓 题解
    弹性碰撞问题:Ants+Linear world
    BZOJ1294 洛谷P2566 状态压缩DP 围豆豆
    朋友HDU
    树的深度———树形DP
    CF1292C Xenon's Attack on the Gangs 题解
  • 原文地址:https://www.cnblogs.com/lvchengda/p/12618223.html
Copyright © 2020-2023  润新知