老司机都知道的Python语法小技巧

作者: 伊洛的小屋 | 来源:发表于2019-12-26 14:44 被阅读0次
    写在前面---Python的优势在于

    1.与主要平台和操作系统兼容
    2.许多开源框架和工具
    3.可读且可维护的代码
    4.强大的标准库
    5.标准测试驱动的开发

    本文首发于伊洛的个人博客:https://yiluotalk.com,欢迎关注并查看更多内容!!!

    • 话不多说了,本文是第二部分,将讲简单的列出几条日常工作中使用Python可能会用到的语法小技巧,希望会对你的工作有所帮助 just enjoy!
      第一部分是:老司机都知道的Python语法小技巧 (一)
    14.列表中元素出现的个数
    # 伊洛Yiluo
    # https://yiluotalk.com
    >>> from collections import Counter
    >>> list = [1,2,3,4,5,1,2,3,4,5,6]
    >>> count = Counter(list)
    >>> count
    Counter({1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 1})
    
    15.列表中查找出现最多的元素
    # 伊洛Yiluo
    # https://yiluotalk.com
    >>> def most_frequement(list):
    ...     return max(set(list), key = list.count)
    ...
    >>> number = [1,2,3,4,5,6,5,5,5,5,5]
    >>> most_frequement(number)
    5
    
    16. 将角度从度转换为弧度
    # 伊洛Yiluo
    # https://yiluotalk.com
    >>> import math
    >>> def degrees_to_radians(deg):
    ...     return (deg * math.pi) / 180
    >>> degrees_to_radians(90)
    1.5707963267948966
    
    17. 计算执行一段代码所花费的时间(非装饰器)
    # 伊洛Yiluo
    # https://yiluotalk.com
    import time
    start_time = time.time()
    a, b = 10, 20
    c = a + b
    end_time = time.time()
    time_taken = (end_time- start_time)*(10**6)
    print('耗时', time_taken)
    
    
    output
    耗时 2.1457672119140625
    
    Process finished with exit code 0
    
    18. 字符串去重
    # 伊洛Yiluo
    # https://yiluotalk.com
    >>> string = "aabbccddeeffgg"
    >>> unique = set(string)
    >>> unique
    {'a', 'f', 'b', 'g', 'c', 'e', 'd'}
    >>> new_string = ''.join(unique)
    >>> new_string
    'afbgced'
    
    19. 使用lambda表达式
    # 伊洛Yiluo
    # https://yiluotalk.com
    >>> x = lambda a, b, c :a + b + c
    >>> print(x(1, 2, 3))
    6
    
    20. 使用 filter
    # 伊洛Yiluo
    # https://yiluotalk.com
    >>> arr = [1, 2, 3, 4, 5]
    >>> arr = list(filter(lambda x : x%2 == 0, arr))
    >>> print(arr)
    [2, 4]
    
    21. 列表
    # 伊洛Yiluo
    # https://yiluotalk.com
    >>> number = [1, 2, 3]
    >>> squares = [number**2 for number in number]
    >>> print(squares)
    [1, 4, 9]
    
    22. 切片
    # 伊洛Yiluo
    # https://yiluotalk.com
    >>> def rotate(arr, d):
    ...     return arr[d:] + arr[:d]
    ...
    >>> arr = [1,2,3,4,5]
    >>> arr = rotate(arr, 2)
    >>> print(arr)
    [3, 4, 5, 1, 2]
    
    23. 链式函数
    # 伊洛Yiluo
    # https://yiluotalk.com
    >>> def subtract(a, b):
    ...     return a - b
    ...
    >>> def add(a, b):
    ...     return a + b
    ...
    >>> def subtract(a, b):
    ...     return a - b
    ...
    >>> a, b = 5, 10
    >>> print((subtract if a > b else add)(a, b))
    15
    >>> a, b = 10, 5
    >>> print((subtract if a > b else add)(a, b))
    5
    

    欢迎下方【戳一下】【点赞】
    Author:伊洛Yiluo
    愿你享受每一天,Just Enjoy !

    相关文章

      网友评论

        本文标题:老司机都知道的Python语法小技巧

        本文链接:https://www.haomeiwen.com/subject/mlikoctx.html