• Python入门示例系列37 常用函数


    datetime

    random

    math

    any, all

    map, reduce, filter

    zip

    datetime

    当前时间戳
    import time  # 引入time模块
    
    ticks = time.time()
    print ("当前时间戳为:", ticks)
    
    # 当前时间戳为: 1648174499.173589
    本地时间
    import time
    
    localtime = time.asctime( time.localtime(time.time()) )
    print ("本地时间为 :", localtime)
    
    #本地时间为 : Fri Mar 25 10:15:55 2022

    格式化时间

    import time
    
    # 格式化成2022-03-20 11:45:39形式
    print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    
    # 格式化成Sat Mar 28 22:24:24 2022形式
    print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
     
    # 将格式字符串转换为时间戳
    a = "Sat Mar 28 22:24:24 2022"
    print (time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))

     日历

    import calendar
    
    cal = calendar.month(2022, 3)
    print ("以下输出2022年3月份的日历:")
    print (cal)
    输出
    以下输出2022年3月份的日历:
         March 2022
    Mo Tu We Th Fr Sa Su
        1  2  3  4  5  6
     7  8  9 10 11 12 13
    14 15 16 17 18 19 20
    21 22 23 24 25 26 27
    28 29 30 31

    random

    import random
    
    print( random.randint(1,10) )        # 产生 1 到 10 的一个整数型随机数(10 不能取)  
    print( random.random() )             # 产生 0 到 1 之间的随机浮点数
    print( random.uniform(1.1,5.4) )     # 产生  1.1 到 5.4 之间的随机浮点数,区间可以不是整数
    print( random.choice('tomorrow') )   # 从序列中随机选取一个元素
    print( random.randrange(1,100,2) )   # 生成从1到100的间隔为2的随机整数
    
    a=[1,3,5,6,7]                # 将序列a中的元素顺序打乱
    random.shuffle(a)
    print(a)

    输出

    5
    0.5859022749835326
    3.410849075465223
    o
    15
    [1, 5, 3, 6, 7]

    math

    >>> import math
    >>> dir(math)
    ['__doc__', '__file__', '__loader__', '__name__', '__package__',
    '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2',
    'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf',
    'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod',
    'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose',
    'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10',
    'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin',
    'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

    any, all

    any() 函数用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。

    元素除了是 0、空、FALSE 外都算 TRUE。

    >>>any(['a', 'b', 'c', 'd'])  # 列表list,元素都不为空或0
    True
     
    >>> any(['a', 'b', '', 'd'])   # 列表list,存在一个为空的元素
    True
     
    >>> any([0, '', False])        # 列表list,元素全为0,'',false
    False
     
    >>> any(('a', 'b', 'c', 'd'))  # 元组tuple,元素都不为空或0
    True
     
    >>> any(('a', 'b', '', 'd'))   # 元组tuple,存在一个为空的元素
    True
     
    >>> any((0, '', False))        # 元组tuple,元素全为0,'',false
    False
      
    >>> any([]) # 空列表
    False
     
    >>> any(()) # 空元组
    False

    all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。

    元素除了是 0、空、None、False 外都算 True。

    >>> all(['a', 'b', 'c', 'd'])  # 列表list,元素都不为空或0
    True
    >>> all(['a', 'b', '', 'd'])   # 列表list,存在一个为空的元素
    False
    >>> all([0, 1,2, 3])          # 列表list,存在一个为0的元素
    False
       
    >>> all(('a', 'b', 'c', 'd'))  # 元组tuple,元素都不为空或0
    True
    >>> all(('a', 'b', '', 'd'))   # 元组tuple,存在一个为空的元素
    False
    >>> all((0, 1, 2, 3))          # 元组tuple,存在一个为0的元素
    False
       
    >>> all([])             # 空列表
    True
    >>> all(())             # 空元组
    True

    map, reduce, filter

    map() 函数会根据提供的函数对指定序列做映射。
    第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
    以下是 map() 方法的语法:
    map(function, iterable, ...)
    参数:function -- 函数;iterable -- 一个或多个序列。
    返回值:返回一个迭代器。

    以下实例展示了 map() 的使用方法:

    >>> def square(x) :         # 计算平方数
    ...     return x ** 2
    ...
    >>> map(square, [1,2,3,4,5])    # 计算列表各个元素的平方
    <map object at 0x100d3d550>     # 返回迭代器
    >>> list(map(square, [1,2,3,4,5]))   # 使用 list() 转换为列表
    [1, 4, 9, 16, 25]
    >>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))   # 使用 lambda 匿名函数
    [1, 4, 9, 16, 25]
    >>>


    reduce() 函数会对参数序列中元素进行累积。
    函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
    注意:Python3.x reduce() 已经被移到 functools 模块里,如果我们要使用,需要引入 functools 模块来调用 reduce() 函数:from functools import reduce
    reduce() 函数语法:
    reduce(function, iterable[, initializer])
    参数:function -- 函数,有两个参数; iterable -- 可迭代对象;initializer -- 可选,初始参数。
    返回值:返回函数计算结果。

    以下实例展示了 reduce() 的使用方法:
    实例

    from functools import reduce
    
    def add(x, y) :            # 两数相加
        return x + y
    sum1 = reduce(add, [1,2,3,4,5])   # 计算列表和:1+2+3+4+5
    sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函数
    print(sum1)
    print(sum2)

    以上实例输出结果为:
    15
    15

    filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
    该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
    以下是 filter() 方法的语法:
    filter(function, iterable)
    参数:function -- 判断函数。iterable -- 可迭代对象。
    返回值:返回一个迭代器对象。
    以下展示了使用 filter 函数的实例:
    过滤出列表中的所有奇数:

    def is_odd(n):
        return n % 2 == 1
     
    tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    newlist = list(tmplist)
    print(newlist)

    输出结果 :
    [1, 3, 5, 7, 9]

    过滤出1~100中平方根是整数的数:

    import math
    def is_sqr(x):
        return math.sqrt(x) % 1 == 0
     
    tmplist = filter(is_sqr, range(1, 101))
    newlist = list(tmplist)
    print(newlist)

    输出结果:
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

    zip

    zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
    我们可以使用 list() 转换来输出列表。
    如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
    zip 语法:zip([iterable, ...])
    参数说明:iterabl -- 一个或多个迭代器;
    返回值:返回一个对象。

    以下实例展示了 zip 的使用方法:
    实例

    >>> a = [1,2,3]
    >>> b = [4,5,6]
    >>> c = [4,5,6,7,8]
    >>> zipped = zip(a,b)     # 返回一个对象
    >>> zipped
    <zip object at 0x103abc288>
    >>> list(zipped)  # list() 转换为列表
    [(1, 4), (2, 5), (3, 6)]
    >>> list(zip(a,c))              # 元素个数与最短的列表一致
    [(1, 4), (2, 5), (3, 6)]
    
    >>> a1, a2 = zip(*zip(a,b))          # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
    >>> list(a1)
    [1, 2, 3]
    >>> list(a2)
    [4, 5, 6]
    >>>




    REF

    https://www.runoob.com/python3/python3-date-time.html

    https://www.runoob.com/python/func-number-random.html

    https://www.runoob.com/python/python-func-all.html

    https://www.runoob.com/python/python-func-any.html

    https://www.runoob.com/python3/python3-func-map.html

    https://www.runoob.com/python/python-func-filter.html

    https://www.runoob.com/python3/python3-func-zip.html

  • 相关阅读:
    kafka+zookeeper集群部署
    rabbitmq集群部署
    nginx location语法
    rabbitmq单一部署
    Centos6国内可用yum源
    css
    imutable
    js解构复制语法
    redux
    json server问题
  • 原文地址:https://www.cnblogs.com/emanlee/p/16053633.html
Copyright © 2020-2023  润新知