Python自动化开发03

集合

1、去重

list_1 = set([1,2,3,4,0,7,4,8])

list2 = set([99,34,6,8,3])

list3 = set([0,4,8])

list4 = set([84,45,49])

print(list_1) <<< {0, 1, 2, 3, 4, 7, 8}

2、 交集

list_1 & list2

print(list_1.intersection(list2)) <<< {8, 3}

3、并集(合集)

list_1 | list2

print(list_1.union(list2)) <<< {0, 1, 2, 3, 4, 99, 34, 7, 8, 6}

4、子集

print(list_1.issubset(list2))   <<<  False

5、父集

print(list_1.issuperset(list3)) <<< True

6、差集

list_1 - list2

print(list_1.difference(list2)) <<< {0, 1, 2, 4, 7}

7、补集

list_1 ^ list2

print(list_1.symmetric_difference(list2)) <<< {0, 1, 34, 99, 2, 6, 4, 7}

8、判断是否有交集(没有为true

print(list_1.isdisjoint(list4)) <<< True

9、小知识点补充

list_1.add(59)    #添加

list_1.update([10,37,42])  #添加多项

list_1.remove(8)   #删除指定项,没找到会报错

list_1.discard(88)   #删除指定项,没找到不报错

list_1.pop()   #随机删除

 文件操作

f = open("file.txt","r",encoding="utf-8")

f.read()  ----> 一次性读所有

f.readline()   -----> 每次读取一行

f.readlines()  ----> 读取文件所有行,生成一个列表,每行为一个元素(只适合于读小文件)

f.tell()   ----> 当前文件所在的指针,按字符个数计数

f.seek(0)  -----> 指针回到最开始位置

f.encoding  -----> 文件字符编码

f.seekable  ----->  判断是否能移动指针位置(True/False

f.flush()   ------->  写入文件时不一定及时写入到硬盘,可能还在缓存中,flush可以用于刷新使之写入到硬盘(缓存写到一定值才会写入硬盘)

f.truncate(10)   ------>  从头开始截断,不管指针在哪

 ##### example #######(内存中只保存一行,可读取大文件,读一行覆盖一行)

for line in f:

    print(line)

 ########## 打印进度条 ##########

import sys,time

for i in range(50):

    sys.stdout.write("#")

    sys.stdout.flush()

    time.sleep(0.1)

 r只读;r+可读可写;两都都不创建

w新建只写,不能读;

w+新建读写,二者都会将文件内容清零

w+r+区别:r+: 可读可写,若文件不存在,报错;w+: 可读可写,若文件不存在,创建

########### r+a+区别 ############

fd = open("1.txt",'w+')  

fd.write('123')  

fd = open("1.txt",'r+')  

fd.write('456')  

fd = open("1.txt",'a+')  

fd.write('789')  

结果:456789

 说明r+进行了覆盖写。

a,a+的方式打开文件,附加方式打开

a:附加写方式打开,不可读;a+: 附加读写方式打开)

  'U' 标志打开文件, 所有的行分割符通过 Python 的输入方法(#read*() ),返回时都会被替换为换行符 . ('rU' 模式也支持 'rb' 选项) .

rU要求文件必须存在

不可读的打开方式:wa

若不存在会创建新文件的打开方式:aa+ww+

函数数初识

 1、函数优点

(1) 减少重复代码

(2) 代码统一性

(3) 可扩展性

 2、非固定参数

def test1(x, *args):

   print(x)

   print(args)

def test2(x,**kwargs)

   print(x)

   print(kwargs)

*args  ----> 接收位置参数变成了元组(包括字典,元组)

**kwargs  -----> 接收关键字参数转成字典

注意: 关键字参数不能写在位置参数前面

 3、形参和实参

 

4、局部变量与全局变量

局部变量只在函数里生效,不会改变全局变量的值

school = "oldboy"

def change_name(name):

    global school    # 定义全局变量可更改school

    school = "Mage"

    print("before change",name,school)

    name = "Alex Li"

    print("after change",name)

 change_name('alex')

print(school)

>>> before change alex Mage

>>> after change Alex Li

>>> Mage

 字符串跟整数不能在函数中改全局变量,列表、字典、集合都是可以在函数里面改的

注意: 不应该在函数中改全局变量

 5、递归特性

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

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

(3) 递归效率不高,递归层次过多会导致栈溢出

 6、函数与函数式编程

面向对象 ---> ----> class

面向过程 ----> 过程 ----> def

函数式编程 ----> 函数 ----> def

函数式编程:只要输入是确定的,输出也是确定的

原文地址:https://www.cnblogs.com/sshcy/p/7801577.html