学习笔记(四)集合、文件与函数

来源:互联网 发布:小米网络解锁 编辑:程序博客网 时间:2024/05/17 09:05

1.集合也是无序的

list_1=[1,4,5,7,3,6,7,9]list_2=set([2,6,0,66,22,8,4])list_1.intersection(list_2)#交集  list_1 & list_2list_1.union(list_2)#并集  list_1 | list_2list_1.symmetric_difference(list_2)#对称差集    list_1 ^ list_2list_1.difference(list_2)#差集    list_1 - list_2list_1.issubset(list_2)#父集list_1.issubset(list_2)#子集

2.文件

  操作流程    1.打开文件,获取句柄        file=open("文件名",encoding="UTF-8")        with open("文件名","r",encoding="UTF-8") as file:    2.通过句柄对文件进行操作        file.read()#默认读所有        file.write()        file.close()        file.readline()        '''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.'''        for i in file:#一行一行的读入            print(i)        file.readlines()#list of strings, each a line from the file.        for index,value in enumerate(file.readline()):#一次性读入文件        #enumerate(iterable[, start]) -> iterator for index, value of iterable            print (index)        file.tell()#int值 Current file position  按字符长度        file.seek()#file.seek()# Move to new file position.        file.flush()#Flush the write buffers of the stream if applicable.        file.truncate()#Truncate the file to at most size bytes from the current file position    3.关闭文件    file.close()

3.函数

def test(*args):#以元组参数,给函数传递不固定参数        print (args)    test(1,2,3,4,5)    def test1(*args):#以元组参数,给函数传递不固定参数        print (args)    test1(*[1,2,3,4,5])    def test2(**args):#将关键字参数以字典形式        print (args)    test2(name='111',age=222)    test2(**{'name':'111','age':222} )    #高阶函数---将函数本身当做参数传递给另一个函数    def add(a,b,f):        return f(a)+f(b)    print (add(3,-6,abs))

4.字节码

   str="你好"    str1=str.decode("gbk")    print(str1)    print(sys.getdefaultencoding())
    for i in range(50):    sys.stdout.write("■")    sys.stdout.flush()    time.sleep(0.1)
原创粉丝点击