• Python3.x基础学习-函数用法(二)


    前言

      Python为我们提供了丰富的内置函数,现在我们来了解一下常用的函数

    内置函数

    求商和余数 divmod()

    ret = divmod(11,2)
    print(ret)
    # (5, 1)

    求绝对值  abs()

    ret = abs(-100)
    print(ret)
    # 100

    求最大值 max()

    ret = max(10,20)
    print(ret)
    # 20



    # 其中 iterable 为可迭代对象,max 会 for i in … 遍历一遍这个迭代器,
    # 然后将每一个返回值当做参数传给 key=func 中的 func(一般用 lambda 表达式定义),
    # 然后将 func 的执行结果传给 key,然后以 key 为标准进行大小的 判断。


    list1 = [2,1,8,-23,6]
    temp = list1[0]

    print(max(list1,key=abs))

    #使用max()函数,找出年龄最大的那组信息
    lst = [
    [1001,'zs',20], #学号,姓名,年龄
    [1002,'ss',25],
    [1003,'ww',22],
    ]

    def func(lst):
    return lst[:][2]
    print(max(lst,key=func))

    #使用max()函数找出出现次数最多的字符
    a = '123456789012345225689233'
    print(a.count('1'))
    print(max(a,key=a.count))
     

    求最小值 min()

    ret = min(10,20)
    print(ret)
    # 10


    传入一个函数和一个可迭代对象 filter(function, iterable)

    filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成 的新列表。
    该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递 给函数进行判断,
    然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
    # 过滤列表中所有偶数
    x = [1,2,3,3,4,4,2,6] def func(n): return n%2==0 ret = filter(func,x) print(list(ret)) # [2, 4, 4, 2, 6]

    #过滤列表中的所有奇数
    lst = [1,2,3,4,5,6,7,8,9]
    def func(num):
    if num%2==1:
    return True
    else:
    return False
    ret = filter(func,lst)
    print(ret)
    # <filter object at 0x000002D15EC4F9B0>
    print(list(ret))
    # [1, 3, 5, 7, 9]


    map(func,iterable)

    map(func,iterable)有两个参数,第一个参数是一个函数,第二个参数是可迭代的内容。
    函数会依次作用在可迭代内容的每一个元素上进行计算,然后返回一个新的可迭代内容。

    # 求列表中每个元素的平方值
    lst =[1,2,3]
    def func(i):
        return i*i
    
    ret =map(func,lst)
    ret1 = filter(func,lst)
    print(list(ret))
    # [1, 4, 9]
    print(list(ret1))
    # [1, 2, 3]

    # 求两个列表中元素相加的和 lst1 = [1,2,3,4,5,6,7,8] lst2 = [2,3,4,5,6] def func(x,y): return x+y ret =list(map(func,lst1,lst2)) print(ret) # [3, 5, 7, 9, 11]

    zip(list1,list2)

    zip 函数接受任意多个可迭代对象作为参数,将对象中对应的元素打包成一个 tuple, 然后返回一个可迭代的zip对象.
    这个可迭代对象可以使用循环的方式列出其元素,若多个可迭代对象的长度不一致,则所返回的列表与长度最短的可迭代对象相同。
    list1 =[1,2,3]
    list2 =[3,2,1]
    ret = zip(list1,list2)
    print(list(ret))
    # [(1, 3), (2, 2), (3, 1)]
    # print(tuple(ret))
    
    str1 ='abc'
    str2 = 'de1f123'
    ret =zip(str1,str2)
    print(tuple(ret))
    # (('a', 'd'), ('b', 'e'), ('c', '1'))
    
    tup1 = ('a','b')
    tup2 = ('c','d')
    # #生成[{'a':'c'},{'b':'d'}]
    
    list1=[]
    def func(tup):
        return {tup[0]:tup[1]}
    ret2 = map(func,ret)
    print(list(ret2))
    # [{'a': 'c'}, {'b': 'd'}]
  • 相关阅读:
    linux系统禁止root用户通过ssh登录及ssh的访问控制
    POJ 3670 , 3671 LIS
    hello world是怎样运行的?
    MFC框架中消失的WinMain()
    [置顶] android LBS的研究与分享(附PPT)
    POJ 3616 DP
    IMP 导入数据报错 OCI-21500 OCI-22275
    误删/tmp导致hadoop无法启停, jsp无法查看的解决方法
    java的文件操作类File
    C#的可空类型与不可空类型
  • 原文地址:https://www.cnblogs.com/johnsonbug/p/12700103.html
Copyright © 2020-2023  润新知