本节内容
- 集合操作
- 文件操作
- 字符编码与转码
- 函数
- 函数参数与局部变量
- 返回值
1、集合操作
集合是一个无序的,不重复的数据组合,它的主要作用如下:
- 去重,把一个列表变成集合,就自动去重了
- 关系测试,测试两组数据之前的交集、差集、并集等关系
常用操作
s = set([3,5,9,10]) #创建一个数值集合 t = set("Hello") #创建一个唯一字符的集合 a = t | s # t 和 s的并集 b = t & s # t 和 s的交集 c = t – s # 求差集(项在t中,但不在s中) d = t ^ s # 对称差集(项在t或s中,但不会同时出现在二者中) 基本操作: t.add('x') # 添加一项 s.update([10,37,42]) # 在s中添加多项 使用remove()可以删除一项: t.remove('H') len(s) set 的长度 x in s 测试 x 是否是 s 的成员 x not in s 测试 x 是否不是 s 的成员 s.issubset(t) s <= t 测试是否 s 中的每一个元素都在 t 中 s.issuperset(t) s >= t 测试是否 t 中的每一个元素都在 s 中 s.union(t) s | t 返回一个新的 set 包含 s 和 t 中的每一个元素 s.intersection(t) s & t 返回一个新的 set 包含 s 和 t 中的公共元素 s.difference(t) s - t 返回一个新的 set 包含 s 中有但是 t 中没有的元素 s.symmetric_difference(t) s ^ t 返回一个新的 set 包含 s 和 t 中不重复的元素 s.copy() 返回 set “s”的一个浅复制
2、文件操作
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game 10 我戏弄生命 视其为愚蠢的游戏 11 The way the evening breeze 12 就如夜晚的微风 13 May tease the candle flame 14 逗弄蜡烛的火苗 15 The thousand dreams I dreamed 16 我曾千万次梦见 17 The splendid things I planned 18 那些我计划的绚丽蓝图 19 I always built to last on weak and shifting sand 20 但我总是将之建筑在易逝的流沙上 21 I lived by night and shunned the naked light of day 22 我夜夜笙歌 逃避白昼赤裸的阳光 23 And only now I see how the time ran away 24 事到如今我才看清岁月是如何匆匆流逝 25 Yesterday when I was young 26 昨日当我年少轻狂 27 So many lovely songs were waiting to be sung 28 有那么多甜美的曲儿等我歌唱 29 So many wild pleasures lay in store for me 30 有那么多肆意的快乐等我享受 31 And so much pain my eyes refused to see 32 还有那么多痛苦 我的双眼却视而不见 33 I ran so fast that time and youth at last ran out 34 我飞快地奔走 最终时光与青春消逝殆尽 35 I never stopped to think what life was all about 36 我从未停下脚步去思考生命的意义 37 And every conversation that I can now recall 38 如今回想起的所有对话 39 Concerned itself with me and nothing else at all 40 除了和我相关的 什么都记不得了 41 The game of love I played with arrogance and pride 42 我用自负和傲慢玩着爱情的游戏 43 And every flame I lit too quickly, quickly died 44 所有我点燃的火焰都熄灭得太快 45 The friends I made all somehow seemed to slip away 46 所有我交的朋友似乎都不知不觉地离开了 47 And only now I'm left alone to end the play, yeah 48 只剩我一个人在台上来结束这场闹剧 49 Oh, yesterday when I was young 50 噢 昨日当我年少轻狂 51 So many, many songs were waiting to be sung 52 有那么那么多甜美的曲儿等我歌唱 53 So many wild pleasures lay in store for me 54 有那么多肆意的快乐等我享受 55 And so much pain my eyes refused to see 56 还有那么多痛苦 我的双眼却视而不见 57 There are so many songs in me that won't be sung 58 我有太多歌曲永远不会被唱起 59 I feel the bitter taste of tears upon my tongue 60 我尝到了舌尖泪水的苦涩滋味 61 The time has come for me to pay for yesterday 62 终于到了付出代价的时间 为了昨日 63 When I was young 64 当我年少轻狂
基本操作
1 f = open('yesterday') #打开文件 2 first_line = f.readline() 3 print('first line:',first_line) #读一行 4 print('我是分隔线'.center(50,'-')) 5 data = f.read()# 读取剩下的所有内容,文件大时不要用 6 print(data) #打印文件 7 8 f.close() #关闭文件
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
def close(self): # real signature unknown; restored from __doc__ """ Close the file. A closed file cannot be used for further I/O operations. close() may be called more than once without error. """ pass def fileno(self, *args, **kwargs): # real signature unknown """ Return the underlying file descriptor (an integer). """ pass def isatty(self, *args, **kwargs): # real signature unknown """ True if the file is connected to a TTY device. """ pass def read(self, size=-1): # known case of _io.FileIO.read """ 注意,不一定能全读回来 Read at most size bytes, returned as bytes. Only makes one system call, so less data may be returned than requested. In non-blocking mode, returns None if no data is available. Return an empty bytes object at EOF. """ return "" def readable(self, *args, **kwargs): # real signature unknown """ True if file was opened in a read mode. """ pass def readall(self, *args, **kwargs): # real signature unknown """ Read all data from the file, returned as bytes. In non-blocking mode, returns as much as is immediately available, or None if no data is available. Return an empty bytes object at EOF. """ pass def readinto(self): # real signature unknown; restored from __doc__ """ Same as RawIOBase.readinto(). """ pass #不要用,没人知道它是干嘛用的 def seek(self, *args, **kwargs): # real signature unknown """ Move to new file position and return the file position. Argument offset is a byte count. Optional argument whence defaults to SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values are SEEK_CUR or 1 (move relative to current position, positive or negative), and SEEK_END or 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). Note that not all file objects are seekable. """ pass def seekable(self, *args, **kwargs): # real signature unknown """ True if file supports random-access. """ pass def tell(self, *args, **kwargs): # real signature unknown """ Current file position. Can raise OSError for non seekable files. """ pass def truncate(self, *args, **kwargs): # real signature unknown """ Truncate the file to at most size bytes and return the truncated size. Size defaults to the current file position, as returned by tell(). The current file position is changed to the value of size. """ pass def writable(self, *args, **kwargs): # real signature unknown """ True if file was opened in a write mode. """ pass def write(self, *args, **kwargs): # real signature unknown """ Write bytes b to file, return number written. Only makes one system call, so not all of the data may be written. The number of bytes actually written is returned. In non-blocking mode, returns None if the write would block. """ pass
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
1 with open('log','r') as f: 2 3 # with又支持同时对多个文件的上下文进行管理 4 with open('log1') as obj1, open('log2') as obj2: 5 pass
3、 字符编码与转码
在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
1 #-*-coding:gb2312 -*- #这个也可以去掉 2 __author__ = 'Xmy' 3 4 import sys 5 print(sys.getdefaultencoding()) 6 7 8 msg = "我爱北京天安门" 9 #msg_gb2312 = msg.decode("utf-8").encode("gb2312") 10 msg_gb2312 = msg.encode("gb2312") #默认就是unicode,不用再decode,喜大普奔 11 gb2312_to_unicode = msg_gb2312.decode("gb2312") 12 gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8") 13 14 print(msg) 15 print(msg_gb2312) 16 print(gb2312_to_unicode) 17 print(gb2312_to_utf8) 18 19 # in python3
4、函数
定义
函数是指将一组语句的集合通过一个名字(函数名)封装起来。想要执行这个函数,只需要调用其函数名即可。
特性
1、减少重复代码
2、使程序变得可扩展
3、使程序变得易维护
语法定义
1 def sayhi():#函数名 2 print("Hello, I'm nobody!") 3 4 sayhi() #调用函数
可以带参数
1 #下面这段代码 2 a,b = 5,8 3 c = a**b 4 print(c) 5 6 7 #改成用函数写 8 def calc(x,y): 9 res = x**y 10 return res #返回函数执行结果 11 12 c = calc(a,b) #结果赋值给c变量 13 print(c)
5、函数参数与局部变量
形参变量只有在被调用时才分配内存单元,在调用结束时,即刻释放所分配的内存单元。因此,形参只在函数内部有效。函数调用结束返回主调用函数后则不能再使用该形参变量。
实参可以是常量、变量、表达式、函数等,无论实参是何种类型的量,在进行函数调用时,它们都必须有确定的值,以便把这些值传送给形参。因此应预先用赋值,输入等办法使参数获得确定值。
默认参数
def stu_register(name, age, country, course): print("----注册学生信息------") print("姓名:", name) print("age:", age) print("国籍:", country) print("课程:", course) stu_register("王山炮", 22, "CN", "python_devops") stu_register("张叫春", 21, "CN", "linux") stu_register("刘老根", 25, "CN", "linux") # 在country参数均为‘CN’时,可以讲其改为默认参数 def stu_register(name,age,course,country="CN"): #定义默认参数 # 该参数在调用时不指定,则默认为CN,指定后则用指定的值
关键参数
正常情况下,给函数传参数要按顺序,不想按顺序就可以用关键参数,只需指定参数名即可,但记住一个要求就是,关键参数必须放在位置参数之后。
非固定参数
若你的函数在定义时不确定用户想传入多少个参数,就可以使用非固定参数
1 # 非固定参数 2 def stu_register(name, age, *args): # *args 会把多传入的参数变成一个元组形式 3 print(name, age, args) 4 5 stu_register("Alex", 22) 6 # 输出 7 Alex 22 () 8 9 stu_register("Jack", 32, "CN", "Python") 10 # 输出 11 Jack 32 ('CN', 'Python') 12 13 stu_register('Tony',26,*['CN','Python']) 14 # 输出 15 Tony 26 ('CN', 'Python') 16 17 18 def stu_register(name, age, *args, **kwargs): # *kwargs 会把多传入的参数变成一个dict形式 19 print(name, age, args, kwargs) 20 21 stu_register("Alex", 22) 22 # 输出 23 Alex 22 () {} 24 25 stu_register("Jack", 32, "CN", "Python", sex="Male", province="ShanDong") 26 # 输出 27 Jack 32 ('CN', 'Python') {'sex': 'Male', 'province': 'ShanDong'} 28 29 stu_register('Tony',26,*['CN','Python'],**{'sex':'M','Province':'Tianjin'}) 30 #输出 31 Tony 26 ('CN', 'Python') {'sex': 'M', 'Province': 'Tianjin'}
局部变量
1 location = 'Beijing' #全局变量 2 3 def change_name(name): 4 # global location #申明在函数中修改全局变量,不建议 5 location = 'Shanghai' 6 print("before change:", name,location) 7 name = "Xmy" #函数是这个变量的作用域,局部变量 8 print("after change", name) 9 10 name = "Alex Li" 11 change_name(name) 12 13 print(location) 14 print("在外面看看name改了么?", name) 15 16 # 输出 17 before change: Alex Li Shanghai 18 after change Xmy 19 Beijing 20 在外面看看name改了么? Alex Li
字典、列表、集合、类可以在局部中直接更改全局
1 names = ['Xmy','Zhb','Yg'] 2 def change_name(): 3 names[0] = '园哥' 4 print('inside function',names) 5 6 change_name() 7 print(names) 8 9 # 输出 10 inside function ['园哥', 'Zhb', 'Yg'] 11 ['园哥', 'Zhb', 'Yg']
6、返回值
要想获取函数的执行结果,就可以用return语句把结果返回
注意:
- 函数在执行过程中只要遇到return语句,就会停止执行并返回结果,so 也可以理解为 return 语句代表着函数的结束
- 如果未在函数中指定return,那这个函数的返回值为None
7、递归
在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
1 def cal(n): 2 print(n) 3 if n/2 > 0: 4 return cal(int(n/2)) 5 print('->',n) 6 7 cal(10) 8 9 # 输出 10 10 11 5 12 2 13 1 14 0 15 -> 0
8、高阶函数
变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
1 def add(a,b,f): 2 return f(a)+f(b) 3 4 res = add(1,-2,abs) 5 print(res) 6 7 # 输出 8 3