zoukankan      html  css  js  c++  java
  • Python高级用法

    Python高级用法

    三元表达式

    x = 10
    y = 20
    print(x if x > y else y)
    x = 100
    y = 20
    print(x if x > y else y)
    

    20

    100

    列表推导式和生成器

    列表推导式

    print([i for i in range(10)])
    print([i*2 for i in range(10)])
    print([i-1 for i in range(10)])
    

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
    [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]

    生成器

    把列表推导式的[]换成()就是生成器表达式

    优点:省内存,一次只产生一个值在内存中

    t = (i for i in range(10))
    print(t)
    print(f"next(t): {next(t)}")
    

    zip()返回一个zip对象,其内部元素为元组;可以转化为列表或者元组

    keys = ['name', 'age', 'gender']
    values = ['nick', 19, 'male']
    res = zip(keys, values)
    print(res)
    for i in res:
        print(i)
    print(F"zip(keys,values): {zip(keys,values)}")
    
    info_dict = {k: v for k, v in res}
    print(f"info_dict: {info_dict}")
    

    <zip object at 0x000001D6D7870E08>
    ('name', 'nick')
    ('age', 19)
    ('gender', 'male')
    zip(keys,values): <zip object at 0x000001D6D7870E88>
    info_dict: {}

    匿名函数

    匿名函数就是一个没有变量名的函数对象

    res = (lambda x, y: x+y)(1, 2)
    print(res)
    print(lambda x, y: x+y)
    

    3
    <function at 0x000001958A013E18>

    应用(一般和内置函数联用)

    匿名函数通常与max()、sorted()、filter()、sorted()方法联用。

    举例filter 匿名

    name_list = ['nick', 'jason sb', 'tank sb', 'sean sb']
    
    filter_res = filter(lambda name: name.endswith('sb'), name_list)
    print(f"list(filter_res): {list(filter_res)}")
    

    list(filter_res): ['jason sb', 'tank sb', 'sean sb']

    正常函数

    name_list = ['nick', 'jason sb', 'tank sb', 'sean sb']
    def zx(name):
        return name.endswith('sb')
    
    filter_res = filter(zx, name_list)
    print(f"list(filter_res): {list(filter_res)}")
    

    list(filter_res): ['jason sb', 'tank sb', 'sean sb']

  • 相关阅读:
    Java Json 数据下划线与驼峰格式进行相互转换
    php 将数组转换网址URL参数
    Swagger2常用注解及其说明 (转)
    Java中 VO、 PO、DO、DTO、 BO、 QO、DAO、POJO的概念(转)
    bootstrap.css.map 404
    Git发生SSL certificate problem: certificate ha错误的解决方法
    防火墙禁ping:虚拟机ping不通主机,但主机可以ping虚拟机
    PhpStorm本地断点调试
    Java语言中姐种遍历List的方法总结
    Ubuntu18.04安装mysql5.7
  • 原文地址:https://www.cnblogs.com/zx125/p/11348838.html
Copyright © 2011-2022 走看看