zoukankan      html  css  js  c++  java
  • 三元表达式 ,列表推导式 , 字典生成式

    一、三元表达式

    条件成立时的返回值 if 条件 else 条件不成立时的返回值

    x = 10
    y = 20
    
    print(f"x if x > y else y: {x if x > y else y}")
    x if x > y else y: 20

    二、列表推导式

    [expression for item1 in iterable1 if condition1
    for item2 in iterable2 if condition2
    ...
    for itemN in iterableN if conditionN
    ]
    类似于
    res=[]
    for item1 in iterable1:
        if condition1:
            for item2 in iterable2:
                if condition2
                    ...
                    for itemN in iterableN:
                        if conditionN:
                            res.append(expression)
    print(F"[i for i in range(10)]: {[i for i in range(10)]}")
    [i for i in range(10)]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    print(F"[i**2 for i in range(10)]: {[i**2 for i in range(10)]}")
    [i**2 for i in range(10)]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    三、字典生成式

    print({i: i**2 for i in range(10)})
    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

    二、zip()方法

    keys = ['name', 'age', 'gender']
    values = ['nick', 19, 'male']
    
    res = zip(keys, values)
    print(F"zip(keys,values): {zip(keys,values)}")
    
    info_dict = {k: v for k, v in res}
    print(f"info_dict: {info_dict}")
    zip(keys,values): <zip object at 0x11074c088>
    info_dict: {'name': 'nick', 'age': 19, 'sex': 'male'}

    通过解压缩函数生成一个字典

    info_dict = {'name': 'nick', 'age': 19, 'gender': 'male'}
    print(f"info_dict.keys(): {info_dict.keys()}")
    print(f"info_dict.values(): {info_dict.values()}")
    
    res = zip(info_dict.keys(), info_dict.values())
    print(F"zip(keys,values): {zip(info_dict.keys(),info_dict.values())}")
    
    info_dict = {k: v for k, v in res}
    print(f"info_dict: {info_dict}")
    info_dict.keys(): dict_keys(['name', 'age', 'gender'])
    info_dict.values(): dict_values(['nick', 19, 'male'])
    zip(keys,values): <zip object at 0x1105cefc8>
    info_dict: {'name': 'nick', 'age': 19, 'gender': 'male'}
  • 相关阅读:
    uip UDPclient模式通信移植,p本地ort可以是无规
    正则表达式摘要
    Regular expression
    正则-合乎规则
    通配符-通配
    正则表达式总结
    判断大盘筑顶的方法
    筑顶和下跌规律
    股票的筑顶危险信号
    股票筑顶的基本特征
  • 原文地址:https://www.cnblogs.com/lulingjie/p/11412827.html
Copyright © 2011-2022 走看看