zoukankan      html  css  js  c++  java
  • python 基础 day4

    内置函数:

    callable()

    检查f1能否被调用 能返回True

    def f1():
      pass
    print(callable(f1))

    chr()

    返回整数i对应的ASCII字符。与ord()作用相反。

    参数x:取值范围[0, 255]之间的正数。

    import random
    
    i = random.randrange(65,91) #65-91随机数
    c = chr(i)
    print(c)
    Z

    b = ord("A")
    print(b)

    65

    小程序,随机生成验证码:

    for i  in range(6):
         r = random.randrange(0,5)
         if r == 2 or r == 4:
             num = random.randrange(0,10)
             li.append(str(num))
         else:
             temp = random.randrange(65,91) #随机生成验证码
             c = chr(temp)
             li.append(c)
    a = "".join(li) #拼接 元素必须都是字符串
    print(a)
     

    1、读取文件内容open,str到内存

    2、python,把字符串>===编译,解释代码

    3、执行代码

    compile() #将字符串编译成python代码

    exec()     #执行 python代码接收:代码或字符串,没有返回值

    eval()     #执行 把字符串转换表达式,有返回值,只能执行表达式

    #编译, single单行,eval表达式,exec跟python一样的东西
    s = "print(123)"     
    #将字符串编译成python代码
    r = compile(s,"<string>","exec") #要么是<string> 要么是文件名,不能省略,此处的exec和执行的exec没有联系,只表示用exec编译
    #执行
    exec(r) #没有返回值拿不到结果
    s = "8*8"
    ret = eval(s)    #把字符串转成表达式并执行,只能执行表达式,有返回值 ret
    print(ret)

    dir()    #查看获取功能

    help()  #功能详细

    print(dir(dict)) 
    
    help(dict)  

    divmod()

    divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数

    返回结果类型为tuple

    参数:

    a,b可以为数字(包括复数)

    r = divmod(97,10)       #97条,每页显示10条,需要多少页 97 除以10
    print(r)
    (9, 7)    #得9 余7
    n1,n2 = divmod(97,10)   #赋值给n1,n2(可以这样用)

    isinstance()

    在Python中可以使用type()与isinstance()这两个函数判断对象类型,而isinstance()函数的使用上比type更加方便。

    区别:就是对于subclass之类的 type就不行了,所以,强烈建议不要使用type判断对象类型。

    s = "QL"
    r = isinstance(s,str) #判断对象是否是某个类的实例
    pint(r)
    True
    
    s = "QL"
    r = isinstance(s,list) #判断对象是否是某个类的实例
    pint(r)
    False

    filter(函数,可迭代的对象)

    Python内建的filter()函数用于过滤序列。

    和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。

    filter 内部,循环第二个参数,循环内部执行第一个参数

    例如,在一个list中,删掉偶数,只保留奇数,可以这么写:

    def is_odd(n):
      return n % 2 == 1
     
    filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
    # 结果
    [1, 5, 9, 15]

    把一个序列中的空字符串删掉,可以这么写:

    def not_empty(s):
      return s and s.strip()
     
    filter(not_empty, ['A', '', 'B', None, 'C', ' '])
    # 结果
    ['A', 'B', 'C']

    lambda表达式

    f1 = lambda a: a>30      #lambda自动return
    ret = f1(90)
    print(ret)      #返回True
    
    li = [11,22,33,44,55,]
    result = filter(lambda a: a>30,li)   #返回的是True就添加到result,简单的函数就用lambda
    
    print(list(result))
    #结果
    [33, 44, 55]

      li = [11,22,33,44,55]

      result = map(lambda a:a+100,list(filter(lambda a:a>33,li)))

      print (list(result))

      [144, 155]

    map()

    map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。

    map()传入的第一个参数是f,即函数对象本身:

    def f(x):
        return x*x
    
    result = map(f,[1,2,3,4,5,6,7,8,])
    print(result)
    # 结果
    [1, 4, 9, 16, 25, 36, 49, 64]

    把这个list所有数字转为字符串:

    result = map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    print(result)
    #结果
    ['1', '2', '3', '4', '5', '6', '7', '8', '9']

    locals()  #局部变量

    gloabals() #全局变量

    locals 是只读的,globals 不是

    NAME = "QL"
    
    def show():
        a = 123
        b = 123
        
        print(locals())  #局部变量
        print(globals())  #全局变量
        
    show()
    
    #结果
    {'b': 123, 'a': 123}
    {'show': <function show at 0x0000000000D8E488>, '__name__': '__main__', '__doc__': None, 'NAME': 'QL', '__cached__': None, '__file__': 'C:/Users/qinling/PycharmProjects/s13/day3/test2.py', '__spec__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000000006A5C18>, '__builtins__': <module 'builtins' (built-in)>}

    hash() 

    将字符串转成哈希值存在内存中,一般用于字典的key来保存

    s = "sdfsdfsdfsffff"
    
    print(hash(s)) 

    len()

    len()
    s = "李杰"
    print(len(s)) #python3默认按字符计算结果是2,python2只能按字节查看结果是6
    2    
    
    b = bytes(s,encoding='utf-8') #python3按字节查看 需转换一下
    print(b)
    6

    max() #最大

    r = max([11,22,33,1])
    print(r)
    #输出
    33

    min() #最小

    sum() #求和

    #sum是python中一个很实用的函数,但是要注意它的使用,我第一次用的时候,就把它这样用了:
    s = sum(1,2,3)
    #结果就悲剧啦
    #其实sum()的参数是一个list
    #例如:
    sum([1,2,3])
    sum(range(1,11))
    
    #还有一个比较有意思的用法
    a = range(1,11)
    b = range(1,10)
    c =  sum([item for item in a if item in b])
    print c
    
    #输出:
    45

    memoryview()# 内存地址相关的

    object()# 是所有类的父类

    reversed() #反转

    li = [11,22,]
    
    li.reverse()
     print(li)
    
    a = reversed(li)  #两种方法效果是一样的
    print(list(a))

    sort()

    li.sort() #排序 和下面的效果一样
    print(sorted(li))

    zip()

    zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压)。

    l1 = ["how",11,22,33,]
    l2 = ["are",11,22,33,]
    l3 = ["you",11,22,33,]
    
    re = zip(l1,l2,l3)
    print(list(re))
    
    #结果
    [('how', 'are', 'you'), (11, 11, 11), (22, 22, 22), (33, 33, 33)]

    l1 = ["how",11,22,33,]
    l2 = ["are",11,22,33,]
    l3 = ["you",11,22,33,]

    re = zip(l1,l2,l3)

    temp = list(re)[0]
    print(temp)

    ret = ' '.join(temp)

    print(ret) 

    #结果

    ['how', 'are', 'you']

    how are you

     需要掌握的内置函数

    装饰器

    (最常用在权限验证)

    在函数外部修改,之前或之后

    理解:

    def f1():
        print(123)
    
    def f2(xxx):
        xxx()
        
    f2(f1)         #f1代表f1函数整体 xxx()也代表函数整体,函数可以作为参数传递。

    @+函数名,放在某个函数上面,具有的功能:

    1、自动执行outer函数并且将它下面的函数名f当做参数传递

    2、将outer函数的返回值重新赋值给f

    3、一旦被装饰装饰,下面的函数被重新赋值,执行装饰函数的内部函数。

    p1.py
    
    def outer(func):
        def inner():
            print("log")
            func()
            return func()    #func 代指 f2函数   func=f1 func()执行f1函数
        return inner         #inner作为函数整体返回
    
    @outer
    def f2():
        print("f2")
    
    @outer
    def f1():
        print("f1")
    
    p2.py
    import p1
    p1.f2()
    
    #结果
    log
    f2

    可以传多个参数:

    p3.py
    
    def outer(func):
        def inner(*args,**kwargs):
            print("before")
            r = func(*args,**kwargs)
            print("after")
            return r          #func 代指 f1函数   func=f1 func()执行f1函数
        return inner 
    
    @outer
    def f1(arg):
        print(arg)
        return "hello"
    
        
    p4.py
    
    import p3
    
    p3.f1("haha")
    
    
    #运行p4.py结果
    before
    haha
    after
    'hello'

     

    补充:

    shutil 模块用法:

    import shutil
    shutil.copy('userfile.txt', 'file1.txt') #拷贝文件
  • 相关阅读:
    How to build Linux system from kernel to UI layer
    Writing USB driver for Android
    Xposed Framework for Android 8.x Oreo is released (in beta)
    Linux Smartphone Operating Systems You Can Install Today
    Librem 5 Leads New Wave of Open Source Mobile Linux Contenders
    GUADEC: porting GNOME to Android
    Librem 5 – A Security and Privacy Focused Phone
    GNOME and KDE Join Librem 5 Linux Smartphone Party
    Purism计划推出安全开源的Linux Librem 5智能手机
    国产系统之殇:你知道的这些系统都是国外的
  • 原文地址:https://www.cnblogs.com/QL8533/p/5543213.html
Copyright © 2011-2022 走看看