day3-python-集合文件操作函数

一、集合

主要作用: 

  1. 去重
  2. 关系测试, 交集\差集\并集\反向(对称)差集
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)
    
    list_2 = set([2,6,0,66,22,8,4])
    print(list_1,list_2)
    
    #交集
    print(list_1.intersection(list_2))
    print(list_1 & list_2)
    #并集
    print(list_1.union(list_2))
    print(list_2 | list_1)
    #差集 in list_1 but not in list_2
    print(list_1.difference(list_2))
    print(list_1 - list_2)
    print(list_2.difference(list_1))
    #子集
    list_3 = set([1,3,7])
    print(list_3.issubset(list_1))
    #父集
    print(list_1.issuperset(list_3))
    #对称差集
    print(list_1.symmetric_difference(list_2))
    print(list_1 ^ list_2)
    #没有交集
    list_4 = set([5,6,8])
    print(list_3.isdisjoint(list_4))
    #添加
    list_1.add(999)
    list_1.update([888,777,555])
    print(list_1)
    #删除
    list_1.remove(888)
    print(list_1)
    print(list_1.pop()) #随机删除
    list_1.discard(888)

二、文件操作

对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件 

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 自动转换成 (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab
#!/usr/bin/env python
# -*- coding:utf-8 -*-

# data = open("yesterday",encoding="utf-8").read()
# f = open("yesterday2",'w',encoding="utf-8")  #文件句柄
# f = open("yesterday",'r+',encoding="utf-8")  #文件句柄 读写
# f = open("yesterday",'w+',encoding="utf-8")  #文件句柄 写读
f = open("yesterday",'wb')  #文件句柄 二进制文件
f.write("hello binary
".encode())
f.close()
# f.truncate(20) #截断
# print(f.readline())
# print(f.readline())
# print(f.readline())
# print(f.tell())
# f.write("-----------diao--------
")
# f.write("-----------diao--------
")
# f.write("-----------diao--------
")
# f.write("-----------diao--------
")
# print(f.tell())
# f.seek(10)
# print(f.tell())
# print(f.readline())
# f.write("should be at the begining of the second line")


# print(f.readline())
# print(f.readline())
# print(f.tell())
# print(f.readline())
# print(f.readline())
# print(f.readline())
# print(f.tell())
# f.seek(10)
# print(f.readline())
#
# print(f.encoding)
# print(f.fileno())
#
# print(f.flush())
#high bige
'''
count =0
for line in f:
    if count == 9:
        print('---我是分割线---')
        count += 1
        continue
    print(line)
    count +=1
# low loop
'''
'''
for index,line in enumerate(f.readlines()):

    if index == 9:
        print('----我是分割线----')
        continue
    print(line.strip())
'''
#a = append 追加
# for line in f.readlines():
#     print(line.strip())
# # for i in range(5):
#     print(f.readline())
# f.write("when i was young i listen to the radio
")

三、with语句

避免打开文件忘记关闭

#!/usr/bin/env python
# -*- coding:utf-8 -*-

with open("yesterday2","r",encoding="utf-8") as f:
    for line in f:
        print(line)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
f = open("yesterday2","r",encoding="utf-8")
f_new = open("yesterday2.bak","w",encoding="utf-8")
find_str = sys.argv[1]
replace_str = sys.argv[2]
for line in f:
    if find_str in line:
        line = line.replace(find_str,replace_str)
    f_new.write(line)
f.close()
f_new.close()

四、函数

1、定义

函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可

2、特性:

  1. 减少重复代码
  2. 使程序变的可扩展
  3. 使程序变得易维护
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#函数
def func1():
    """testing1"""
    print('in the func1')
    return 0
#过程
def func2():
    """testing2"""
    print('in the func2')

x = func1()
y = func2()

print('from func1 return is %s'%x)
print('from func2 return is %s'%y)

 3、函数参数

形参变量只有在被调用时才分配内存单元,在调用结束时,即刻释放所分配的内存单元。因此,形参只在函数内部有效。函数调用结束返回主调用函数后则不能再使用该形参变量

实参可以是常量、变量、表达式、函数等,无论实参是何种类型的量,在进行函数调用时,它们都必须有确定的值,以便把这些值传送给形参。因此应预先用赋值,输入等办法使参数获得确定值

#!/usr/bin/env python
# -*- coding:utf-8 -*-

def test(x,y,z):
    print(x)
    print(y)
    print(z)

# test(y=2,x=1) #与形参顺序无关
# test(1,2)   #与形参一一对应
# test(x=2,3)
test(3,2,z=6) #关键参数不能写在位置参数前面

4、关键参数

正常情况下,给函数传参数要按顺序,不想按顺序就可以用关键参数,只需指定参数名即可,但记住一个要求就是,关键参数必须放在位置参数之后。

5、非固定参数

若你的函数在定义时不确定用户想传入多少个参数,就可以使用非固定参数

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# def test(*args):
#     print(args)
#
# test(1,2,3,4,5)
# test(*[1,2,4,5,5]) # args=tuple([1,2,4,5,5])
#
# def test1(x,*args):
#     print(x)
#     print(args)
# test1(1,2,3,4,5,6,7)
#
# def test2(**kwargs):
#     print(kwargs)
#     print(kwargs['name'])
#     print(kwargs['age'])
#     print(kwargs['sex'])
#
# test2(name='alex',age=8,sex='F')
# # test2(**{'name':'alex','age':8})
# def test3(name,age=18,**kwargs):
#     print(name)
#     print(age)
#     print(kwargs)
# test3('alex',34,sex='m',hobby='tesla')
def test4(name,age=18,*args,**kwargs):
    print(name)
    print(age)
    print(args)
    print(kwargs)

def logger(source):
    print("from %s" % source)
test4('alex',age=34,sex='m',hobby='tesla')

6、局部变量

#!/usr/bin/env python
# -*- coding:utf-8 -*-

school = "Oldboy edu"
names = ["Alex","Jack","Rain"]
def change_name():
    names[0] = "金角大王"
    print("inside func",names)

change_name()
print(names)

7、全局与局部变量

在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量。
全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序。
当全局变量与局部变量同名时:
在定义局部变量的子程序内,局部变量起作用;在其它地方全局变量起作用。
五、递归函数
在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
#!/usr/bin/env python
# -*- coding:utf-8 -*-

def calc(n):
    print(n)
    if int(n/2) >0:
        return calc(int(n/2))
    print("->",n)
calc(10)

递归特性:

1. 必须有一个明确的结束条件

2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少

3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)

 六、高阶函数

变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。

#!/usr/bin/env python
# -*- coding:utf-8 -*-

def add(a,b,f):
    return f(a)+f(b)

res = add(3,-6,abs)
print(res)

七、作业

参考https://blog.51cto.com/ygqygq2/1876761

原文地址:https://www.cnblogs.com/guantou1992/p/11202349.html