zoukankan      html  css  js  c++  java
  • Python:Python基础(二)

    • lambda表达式

    #函数名 = lambda 参数 :函数体
    f1 = lambda a1,a2 : a1 + a2
    r1 = f1(3,8)
    print(r1)
    #打印结果:11
    •  内置函数

        绝对值:abs()

    i = abs(123)
    print(i)
    #打印结果:123

    r = abs(-123) print(r) #打印结果:123

        循环所有参数:all()

    #all,循环参数,如果每个元素都为真,那么all的返回值为真
    r = all([True])
    print(r)
    #打印结果:True
    #假:0,None,"",[],(),{}==>0,None,空值
    print(bool(None))
    #打印结果:False

        只要一个真,则为真:any()

    i = any([11,22,0])
    print(i)
    #打印结果:True

        

    bin()#二进制
    oct()#八进制
    int()#十进制
    hex()#十六进制

    进制之间的转换:
    #base=2,表示将二进制转换成其他进制
    i = int('0b1011',base = 2)
    print(i)
    #打印结果:11
     去对象的类中找__repr__ ,获取其返回值:ascii(对象) 
    判断真假,把一个对象转换成布尔值:bool()

    字节:bytes
    字节列表:bytearray
    #字节列表:字节里面每一个元素就是一个字节
    字节转字符串:butes("字符串",encoding="utf-8")

    接受一个数字,找到ascii码中对应的一个元素:chr()
    反之就是:ord()
    i = chr(65)
    print(i)
    #打印结果:A
    
    r = ord("A")
    print(r)
    #打印结果:65

         练习:实现随机验证码

    设定一个可能有数字可能有字母的6位随机验证码

     1 #生成一个随机数
     2 #数字转换成字母:chr(数字)
     3 #ascii码中65-90对应的是大写字母
     4 #导入random模块,生成随机数
     5 import random
     6 temp = ""
     7 for i in range(6):
     8     num = random.randrange(0,4)
     9     if num == 3 or num == 1:
    10         rad2 = random.randrange(0,10)
    11         temp = temp + str(rad2)
    12     else:
    13         rad1 = random.randrange(65,91)
    14         c1 = chr(rad1)
    15         temp = temp + c1
    16 print(temp)
    随机验证码

         可执行的对象(函数、类):callable()

    def f1():
        return 123
    f1()
    r = callable(f1)
    print(r)
    #打印结果:True
    
    a = "236456"
    r = callable(a)
    print(r)
    #打印结果:False
    
    r = callable(len)
    print(r)
    #打印结果:True
    callable()

        复数:complex() 

        查看类里面有哪些功能:dir()

    st = str()
    print
    (dir(st)) #打印结果:['__add__', '__class__', '__contains__', '__delattr__',......]

        得到商和余数:divmod()

    a = 10/3
    print(a)
    #打印结果:3.3333333333333335
    r = divmod(10,3)
    print(r)
    #打印结果:(3, 1)

        将字符串str当成有效的表达式来求值并返回计算结果:eval()

    a = 1 + 3
    print(a)
    #打印结果:4
    a = "1 + 3"
    print(a)
    #打印结果:1 + 3
    ret = eval("1 + 3")
    print(ret)
    #打印结果:4

        直接执行python代码:exec()

    exec("for i in range(10):print(i)")

        过滤(符合条件的就获取,不符合条件的就删除):filter(函数,可以迭代的对象)

    def f1(x):
        if x > 22:
            return True
        else:
            return False
    ret = filter(f1,[11,22,33,44])
    for i in ret :
        print(i)
    #打印结果:33 44

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

    def f1(x):
        return x + 100
    ret = map(f1,[1,2,3,4,5])
    for i in ret:
        print(i)

        获取当前代码里所有的全局变量:globals()

        获取所有的局部变量:locals()

        算哈希值,一般用于字典的key的保存:hash()

        判断某个对象是否是由某个类创建的:isinstance()

    li = [11,22]
    r = isinstance(li,list)
    print(r)
    #打印结果:True

        取最大值:max()

        取最小值:min()

    li = [11,22,356,5]
    r = max(li)
    print(r)
    r = min(li)
    print(r)
    #打印结果:356 5

        求指数:pow()

    i = pow(2,10)
    print(i)
    #打印结果:1024

        四舍五入:round() 

    r = round(3.3)
    print(r)
    r = round(3.6)
    print(r)
    #打印结果:3 4  

        求和:sum()

    r = sum([11,22,33,44])
    print(r)
    #打印结果:110

        zip函数接受任意多个序列作为参数,返回一个tuple列表:zip()

    li1 = [11,22,33,44]
    li2 = ["a","b","c","d"]
    r = zip(li1,li2)
    for i in r:
        print(i)
    #打印结果:(11, 'a')
    (22, 'b')
    (33, 'c')
    (44, 'd')
    • 排序sorted()

        一个位一个位地进行比较排序

    li = [1,211,22,3,4]
    print(li)
    li.sort()
    print(li)
    new_li = sorted(li)
    print(new_li)
    #打印结果:[1, 211, 22, 3, 4]
    #打印结果:[1, 3, 4, 22, 211]
    #打印结果:[1, 3, 4, 22, 211]
    • 文件操作open

    步骤:

    一、打开文件

    open(文件路径,模式,编码)

    打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

    打开文件的模式:

    普通的打开方式(默认编码:encoding = "utf-8"):

    • r,只读模式【默认只可读,不可写】
    • w,只写模式【不可读,如果文件不存在则创建,存在则清空内容】
    • x,只写模式【不可读,如果文件不存在则创建,存在则报错】
    • a,追加模式【不可读,如果文件不存在则创建,存在则只追加内容】

    "b"表示以字节的方式操作(字节的方式打开):

    • rb 或 r + b
    • wb 或 w + b  
    • xb 或 x + b
    • ab 或 a + b

    以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

    注:要将字符串直接写在文件中并以字符串的形式体现:.write(bytes("中国",encoding = "utf-8"))

     既想读又想写时:"+"
    • r+,读写【可读,可写】
    • w+,写读【可读,可写】
    • x+,写读【可读,可写】
    • a+,写读【可读,可写】

    注:

    1:以r+方式进行w,直接在末尾追加,指针就在最后了

    调整指针位置:.seek(num)

    获取指针的位置(打开文件时指针为0,起始位置):.tell()

    2:以w+方式,是先清空,在写之后就可以读了,而且写完之后指针到最后,要读的话就.seek(0),就可以读取写的所有内容

    3:x+,如果文件存在,则报错,不存在则创建

    4:a+,打开文件的同时,指针已经到最后,要读的话就.seek(0),就可以读取写的所有内容

    
    

    二、操作文件

    class file(object)
        def close(self): # real signature unknown; restored from __doc__
            关闭文件
            """
            close() -> None or (perhaps) an integer.  Close the file.
             
            Sets data attribute .closed to True.  A closed file cannot be used for
            further I/O operations.  close() may be called more than once without
            error.  Some kinds of file objects (for example, opened by popen())
            may return an exit status upon closing.
            """
     
        def fileno(self): # real signature unknown; restored from __doc__
            文件描述符  
             """
            fileno() -> integer "file descriptor".
             
            This is needed for lower-level file interfaces, such os.read().
            """
            return 0    
     
        def flush(self): # real signature unknown; restored from __doc__
            刷新文件内部缓冲区
            """ flush() -> None.  Flush the internal I/O buffer. """
            pass
     
     
        def isatty(self): # real signature unknown; restored from __doc__
            判断文件是否是同意tty设备
            """ isatty() -> true or false.  True if the file is connected to a tty device. """
            return False
     
     
        def next(self): # real signature unknown; restored from __doc__
            获取下一行数据,不存在,则报错
            """ x.next() -> the next value, or raise StopIteration """
            pass
     
        def read(self, size=None): # real signature unknown; restored from __doc__
            读取指定字节数据
            """
            read([size]) -> read at most size bytes, returned as a string.
             
            If the size argument is negative or omitted, read until EOF is reached.
            Notice that when in non-blocking mode, less data than what was requested
            may be returned, even if no size parameter was given.
            """
            pass
     
        def readinto(self): # real signature unknown; restored from __doc__
            读取到缓冲区,不要用,将被遗弃
            """ readinto() -> Undocumented.  Don't use this; it may go away. """
            pass
     
        def readline(self, size=None): # real signature unknown; restored from __doc__
            仅读取一行数据
            """
            readline([size]) -> next line from the file, as a string.
             
            Retain newline.  A non-negative size argument limits the maximum
            number of bytes to return (an incomplete line may be returned then).
            Return an empty string at EOF.
            """
            pass
     
        def readlines(self, size=None): # real signature unknown; restored from __doc__
            读取所有数据,并根据换行保存值列表
            """
            readlines([size]) -> list of strings, each a line from the file.
             
            Call readline() repeatedly and return a list of the lines so read.
            The optional size argument, if given, is an approximate bound on the
            total number of bytes in the lines returned.
            """
            return []
     
        def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
            指定文件中指针位置
            """
            seek(offset[, whence]) -> None.  Move to new file position.
             
            Argument offset is a byte count.  Optional argument whence defaults to
    (offset from start of file, offset should be >= 0); other values are 1
            (move relative to current position, positive or negative), and 2 (move
            relative to end of file, usually negative, although many platforms allow
            seeking beyond the end of a file).  If the file is opened in text mode,
            only offsets returned by tell() are legal.  Use of other offsets causes
            undefined behavior.
            Note that not all file objects are seekable.
            """
            pass
     
        def tell(self): # real signature unknown; restored from __doc__
            获取当前指针位置
            """ tell() -> current file position, an integer (may be a long integer). """
            pass
     
        def truncate(self, size=None): # real signature unknown; restored from __doc__
            截断数据,仅保留指定之前数据
            """
            truncate([size]) -> None.  Truncate the file to at most size bytes.
             
            Size defaults to the current file position, as returned by tell().
            """
            pass
     
        def write(self, p_str): # real signature unknown; restored from __doc__
            写内容
            """
            write(str) -> None.  Write string str to file.
             
            Note that due to buffering, flush() or close() may be needed before
            the file on disk reflects the data written.
            """
            pass
     
        def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
            将一个字符串列表写入文件
            """
            writelines(sequence_of_strings) -> None.  Write the strings to the file.
             
            Note that newlines are not added.  The sequence can be any iterable object
            producing strings. This is equivalent to calling write() for each string.
            """
            pass
     
        def xreadlines(self): # real signature unknown; restored from __doc__
            可用于逐行读取文件,非全部
            """
            xreadlines() -> returns self.
             
            For backward compatibility. File objects now include the performance
            optimizations previously implemented in the xreadlines module.
            """
            pass
    2.x
    class TextIOWrapper(_TextIOBase):
        """
        Character and line based layer over a BufferedIOBase object, buffer.
        
        encoding gives the name of the encoding that the stream will be
        decoded or encoded with. It defaults to locale.getpreferredencoding(False).
        
        errors determines the strictness of encoding and decoding (see
        help(codecs.Codec) or the documentation for codecs.register) and
        defaults to "strict".
        
        newline controls how line endings are handled. It can be None, '',
        '
    ', '
    ', and '
    '.  It works as follows:
        
        * On input, if newline is None, universal newlines mode is
          enabled. Lines in the input can end in '
    ', '
    ', or '
    ', and
          these are translated into '
    ' before being returned to the
          caller. If it is '', universal newline mode is enabled, but line
          endings are returned to the caller untranslated. If it has any of
          the other legal values, input lines are only terminated by the given
          string, and the line ending is returned to the caller untranslated.
        
        * On output, if newline is None, any '
    ' characters written are
          translated to the system default line separator, os.linesep. If
          newline is '' or '
    ', no translation takes place. If newline is any
          of the other legal values, any '
    ' characters written are translated
          to the given string.
        
        If line_buffering is True, a call to flush is implied when a call to
        write contains a newline character.
        """
        def close(self, *args, **kwargs): # real signature unknown
            关闭文件
            pass
    
        def fileno(self, *args, **kwargs): # real signature unknown
            文件描述符  
            pass
    
        def flush(self, *args, **kwargs): # real signature unknown
            刷新文件内部缓冲区
            pass
    
        def isatty(self, *args, **kwargs): # real signature unknown
            判断文件是否是同意tty设备
            pass
    
        def read(self, *args, **kwargs): # real signature unknown
            读取指定字节数据
            pass
    
        def readable(self, *args, **kwargs): # real signature unknown
            是否可读
            pass
    
        def readline(self, *args, **kwargs): # real signature unknown
            仅读取一行数据
            pass
    
        def seek(self, *args, **kwargs): # real signature unknown
            指定文件中指针位置
            pass
    
        def seekable(self, *args, **kwargs): # real signature unknown
            指针是否可操作
            pass
    
        def tell(self, *args, **kwargs): # real signature unknown
            获取指针位置
            pass
    
        def truncate(self, *args, **kwargs): # real signature unknown
            截断数据,仅保留指定之前数据
            pass
    
        def writable(self, *args, **kwargs): # real signature unknown
            是否可写
            pass
    
        def write(self, *args, **kwargs): # real signature unknown
            写内容
            pass
    
        def __getstate__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __init__(self, *args, **kwargs): # real signature unknown
            pass
    
        @staticmethod # known case of __new__
        def __new__(*args, **kwargs): # real signature unknown
            """ Create and return a new object.  See help(type) for accurate signature. """
            pass
    
        def __next__(self, *args, **kwargs): # real signature unknown
            """ Implement next(self). """
            pass
    
        def __repr__(self, *args, **kwargs): # real signature unknown
            """ Return repr(self). """
            pass
    
        buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    
        _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    3.x

        1.主动将内存里的刷进硬盘:flush()

        2.读取所有内容:.read()

        3.普通方式 :.read(1):读一个字符

        "b"方式:.read(1):读一个字节

        4.仅读取一行数据:.readline()

           同样可以用:

    f = open("xxx","r",encoding = "utf-8")
    for line in f:
        print(line)
    f.close()

        5.截取(依赖于指针,保留指针之前的内容):.truncate()

    三、关闭文件

        打开一个文件:

    with open(xxx,"r") as f:
      pass

        py2.7之后支持同时打开两个文件:

    with open("log1","r") as obj1,open("log2","r") as obj2:
        pass
  • 相关阅读:
    vb 使用Cystal Reports 9小例子
    VB Export sample
    c++文件結束符
    初学PHP:用post传递checkbox
    VB 图片在数据库的导入与导出
    vb 事务sample
    linux查找进程并杀掉进程
    WebRequest 对象的使用
    Asp操作Cookies(设置[赋值]、读取、删除[设置过期时间])
    .net webrequest应用
  • 原文地址:https://www.cnblogs.com/0820-zq/p/5475713.html
Copyright © 2011-2022 走看看