【python之旅】python的基础二

一、集合的操作

  1、什么是集合?

     集合是一个无序的,不重复的数据组合,它的主要作用如下:

  1. 去重:把一个列表变成集合,就自动去重
  2. 关系测试:测试两组数据之前的交集,差集,并集等关系

    2常用的操作

  将列表变成集合

1 list_1 = [1,4,5,7,3,7,6,9]
2 list_1 = set(list_1)
3 print(list_1,type(list_1))
4 执行结果:
5 {1, 3, 4, 5, 6, 7, 9} <class 'set'>  ###set就是集合的意思,重复的数据已经没有了

  添加一个集合,对比list_1,求交集

# Author :GU
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("=============交集=================")
print(list_1.intersection(list_2)) ###intersection()
#执行结果
=============交集=================
{4, 6}

  并集

1 print("=============并集=================")
2 #并集
3 print(list_1.union(list_2))   ###union()
4 #执行结果
5 =============并集=================
6 {0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}

  差集

 1 print(list_1,list_2)
 2 print("=============差集=================")
 3 #差集:1、去掉与2里面交叉的字符2、反之
 4 #1、去掉与2里面交叉的字符#1里面有的,2里面没有的
 5 print(list_1.difference(list_2))
 6 #2、反之
 7 print(list_2.difference(list_1))
 8 #执行结果
 9 {1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}
10 =============差集=================
11 {1, 3, 5, 9, 7}
12 {0, 8, 2, 66, 22}

  子集

 1 print(list_1,list_2)
 2 list_3 = set([1,3,7])
 3 print("=============子集=================")
 4 #子集
 5 print(list_1.issubset(list_2)) #子集
 6 print(list_2.issuperset(list_1))#父集
 7 执行结果:
 8 False
 9 False
10 =============================
11 list_3 = set([1,3,7])
12 print(list_3.issubset(list_1))
13 print(list_1.issuperset(list_3))
14 执行结果:
15 True
16 True

  对称差集

1 print(list_1,list_2)
2 print("=============对称差集=================")
3 #对称差集:去掉交集
4 print(list_1.symmetric_difference(list_2))
5 执行结果:
6 {1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}
7 =============对称差集=================
8 {0, 1, 2, 66, 3, 5, 7, 8, 9, 22}

  如果3与4之间没有交集,则返回为ture

 1 list_3 = set([1,3,7])
 2 list_4 = set([5,6,8])
 3 print(list_3.isdisjoint(list_4))###isdisjoint()
 4 #执行结果
 5 True
 6 ==========================
 7 list_3 = set([1,3,7])
 8 list_4 = set([5,6,8,7])
  print(list_3.isdisjoint(list_4))
9 #执行结果 10 False

  用运算符判断

 1 #交集
 2 print(list_1 & list_2)
 3 #并集
 4 print(list_1 | list_2)
 5 #差集
 6 print(list_1 - list_2)
 7 #对称差集
 8 print(list_1 ^ list_2)
 9 ###执行结果
10 ==============交集================
11 {4, 6}
12 ==============并集================
13 {0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}
14 ==============差集================
15 {1, 3, 5, 9, 7}
16 ==============对称差集================
17 {0, 1, 2, 66, 3, 5, 7, 8, 9, 22}

  3、集合的增删改查

 1 ##添加
 2 list_1.add(999)
 3 print(list_1)
 4 #执行结果
 5 {1, 3, 4, 5, 6, 7, 999, 9}
 6 ##添加多项
 7 list_1.update([777,555,888])
 8 print(list_1)
 9 #执行结果
10 {1, 3, 4, 5, 6, 7, 999, 9, 777, 555, 888}
11 ##删除
12 print(list_1.pop()) ##随机删除
13 print(list_1.pop())
14 print(list_1.pop())
15 print(list_1.pop())
16 #执行结果:
17 1
18 3
19 4
20 5
21 ======================
22 #print(list_1.remove("ddd")) ###用remove删除如果不存在则会报错
23 print(list_1)
24 list_1.discard(888)#这个就不报错
25 print(list_1)
26 执行结果:
27 {1, 3, 4, 5, 6, 7, 999, 9, 777, 555, 888}
28 {1, 3, 4, 5, 6, 7, 999, 9, 777, 555}

  4、其他操作:

 1 len(s)  
 2 set 的长度  
 3   
 4 x in s  
 5 测试 x 是否是 s 的成员  
 6   
 7 x not in s  
 8 测试 x 是否不是 s 的成员  
 9   
10 s.issubset(t)  
11 s <= t  
12 测试是否 s 中的每一个元素都在 t 中  
13   
14 s.issuperset(t)  
15 s >= t  
16 测试是否 t 中的每一个元素都在 s 中  
17   
18 s.union(t)  
19 s | t  
20 返回一个新的 set 包含 s 和 t 中的每一个元素  
21   
22 s.intersection(t)  
23 s & t  
24 返回一个新的 set 包含 s 和 t 中的公共元素  
25   
26 s.difference(t)  
27 s - t  
28 返回一个新的 set 包含 s 中有但是 t 中没有的元素  
29   
30 s.symmetric_difference(t)  
31 s ^ t  
32 返回一个新的 set 包含 s 和 t 中不重复的元素  
33   
34 s.copy()  
35 返回 set “s”的一个浅复制  

二、文件的操作

  1、文件操作的流程

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

  现有的文件如下

 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 当我年少轻狂
View Code

  2、文件的读、写、追加

 1 ###读
 2 f = open("yesterday","r",encoding="utf-8")   ##r读
 3 data = f.read()
 4 print(data)
 5 ##执行结果
 6 Somehow, it seems the love I knew was always the most destructive kind
 7 不知为何,我经历的爱情总是最具毁灭性的的那种
 8 Yesterday when I was young
 9 。。。。。。。。。。。。。。。。。。。。。。
10 ###写
11 f = open("yesterday2","w",encoding="utf-8")  #w写
12 f.write("我爱北京天安门\n")   ##write()
13 f.write("天安门前太阳升\n")
14 执行结果:
15 ##查看yesterday2文件
16 我爱北京天安门
17 天安门前太阳升
18 ###追加
19 f = open("yesterday2","a",encoding="utf-8")   #
20 f.write("我爱北京天安门\n")
21 f.write("天安门前太阳升")
22 f.close()
23 执行结果 查看yesterday2文件
24 我爱北京天安门
25 天安门前太阳升
26 我爱北京天安门
27 天安门前太阳升
28 ###按行读
29 ##读取前5行
30 f = open("yesterday","r",encoding="utf-8")
31 for i in range(5):
32     print(f.readline().strip())
33 执行结果:
34 Somehow, it seems the love I knew was always the most destructive kind
35 不知为何,我经历的爱情总是最具毁灭性的的那种
36 Yesterday when I was young
37 昨日当我年少轻狂
38 The taste of life was sweet
39 ==================
40 #按行读
41 f = open("yesterday","r",encoding="utf-8")
42 for line in f.readlines():
43     print(line.strip())  ###去掉空格和换行
44 ##
45 #跳过第10行low loop
46 count = 0
47 for line in f:
48     if count == 9:
49         print("===================分割线=======================")
50         count +=1
51         continue
52     print(line.strip())
53     count += 1
54 执行结果:
55 Somehow, it seems the love I knew was always the most destructive kind
56 不知为何,我经历的爱情总是最具毁灭性的的那种
57 Yesterday when I was young
58 昨日当我年少轻狂
59 The taste of life was sweet
60 生命的滋味是甜的
61 As rain upon my tongue
62 就如舌尖上的雨露
63 I teased at life as if it were a foolish game
64 ===================分割线=======================
65 The way the evening breeze
66 
67 #打开大文件的正确方法:
68 # for line in f:
69 #     print(line)
View Code

  3、其他操作

 1 ###移动光标
 2 #打印当前文件句柄光标所在位置
 3 f = open("yesterday","r",encoding="utf-8")
 4 print(f.tell())
 5 print(f.readline())
 6 print(f.tell())##打印当前位置
 7 f.seek(10)   ###回到位置为10的地方
 8 print(f.readline())
 9 ##执行结果
10 0
11 Somehow, it seems the love I knew was always the most destructive kind
12 72
13 t seems the love I knew was always the most destructive kind

   4、缓存flush功能

1 import sys,time
2 for i in range(50):
3     sys.stdout.write("#")
4     sys.stdout.flush()
5     time.sleep(0.1)
6 执行结果:
7 ##################################################

   文件的读写,写读,追加写读,读二进制文件

1 #读写
2 f = open("yesterday","r+",encoding="utf-8")
3 #写读
4 f = open("yesterday","w+",encoding="utf-8") 
5 #追加读写
6 f = open("yesterday","a+",encoding="utf-8")
7 #读二进制文件
8 f = open("yesterday","rb",encoding="utf-8"

 

打开文件的模式有:

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

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

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

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

  • rU
  • r+U

"b"表示处理二进制文件

  • rb
  • wb
  • ab

  5、如何修改一个文件:

  原文件

1 So many lovely songs were waiting to be sung
2 有那么多甜美的曲儿等我歌唱
3 So many wild pleasures lay in store for me
4 有那么多肆意的快乐等顾云享受
5 And so much pain my eyes refused to see
6 还有那么多痛苦 我的双眼却视而不见
View Code

 

1 # Author :GU
2 f = open("yesterday2","r",encoding="utf-8")
3 f_new = open("yesterday2.bak","w",encoding="utf-8")
4 for line in  f:
5     if "肆意的快乐等我享受" in line:
6         line = line.replace("肆意的快乐等我享受","肆意的快乐等顾云享受")
7     f_new.write(line)
8 f.close()
9 f_new.close()

 

  执行后生成的新文件

So many lovely songs were waiting to be sung
有那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等顾云享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见

 

  6、with语句

1 with open("yesterday2","r",encoding="utf-8") as f:
2     for line in f:
3         print(line)

 

三、字符的编码与转码

四、函数

  1、对于函数的理解    --摘至天帅老师博客

  面向过程:根据业务逻辑从上到下写垒代码
  函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
  函数作用是你的程序有良好的扩展性、复用性。
  标注:不能死记,
  函数可以理解为一个一个的功能块,你把一个大的功能拆分成一块一块的,用某项功能的时候就去调用某个功能块即可!
  函数可以调用函数!主函数的作用就是把函数进行串联、调用!函数本身是不能自己执行的如果你不调用就永不执行!

  2、自定义函数

  一直遵循:面向过程编程,即:根据业务逻辑从上到下实现功能,其往往用一长段代码来实现指定功能,开发过程中最常见的操作就是粘贴复制,也就是将之前实现的代码块复制到现需功能处,如下

 1 while True:
 2     if cpu利用率 > 90%:
 3         #发送邮件提醒
 4         连接邮箱服务器
 5         发送邮件
 6         关闭连接
 7   
 8     if 硬盘使用空间 > 90%:
 9         #发送邮件提醒
10         连接邮箱服务器
11         发送邮件
12         关闭连接
13   
14     if 内存占用 > 80%:
15         #发送邮件提醒
16         连接邮箱服务器
17         发送邮件
18         关闭连接
19 这就是面向过程的编程,但是如果报警多了的话成百的代码需要添加如何操作呢?在看下面的代码:
20 def 发送邮件(内容)
21     #发送邮件提醒
22     连接邮箱服务器
23     发送邮件
24     关闭连接
25   
26 while True:
27   
28     if cpu利用率 > 90%:
29         发送邮件('CPU报警')
30   
31     if 硬盘使用空间 > 90%:
32         发送邮件('硬盘报警')
33   
34     if 内存占用 > 80%:
35 这个就简洁,干净很多

 

  3、函数式编程

 1 def 函数名(参数):  
 2     ...
 3     函数体
 4     ...
 5 函数的定义主要有如下要点:
 6     def:表示函数的关键字
 7     函数名:函数的名称
 8     函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
 9     参数:为函数体提供数据
10     返回值:当函数执行完毕后,可以给调用者返回数据

 

  4、函数调用

调用方法:

  1.test()执行,()表示调用函数test,()内可以有参数也可没有

参数:

  1.形参和实参

    形参:形式参数,不是实际存在,是虚拟变量。在定义函数和函数体的时候使用形参,目的是在函数调用时接收实参(实参个数,类型应与实参一一对应)

    实参:实际参数,调用函数时传给函数的参数,可以是常量,变量,表达式,函数,传给形参

    区别:形参是虚拟的,不占用内存空间,形参变量只有在被调用时才分配内存单元,实参是一个变量,占用内存空间,数据传送单向,实参传给形参,不能形参传给实参

  2.位置参数和关键字(标准调用:实参与形参位置一一对应;关键字调用:位置无需固定,关键参数是不能写在位置参数前面的)

  3.默认参数

def test(x,y=2):  #默认参数
    print(x) 
    print(y)
test(1,3)
执行结果:
1
3
默认参数的特点:
#调用参数的时候,默认参数可有可无
#用途:默认安装值

 

  4.参数组

  *args

1 def func(*args, **drgs):
2     print(args)
3     print(drgs)
4 #例子:
5 func(11,22,33,44,k1='luotianshuai',k2='shuaige')
6 (11, 22, 33, 44)
7 {'k2': 'shuaige', 'k1': 'luotianshuai'}

  把关键字参数,转换成字典

1 def func(**kwargs):
2     print(kwargs)
3 func(name="alex",agr=8,sex="F")

  5、局部变量:

 1 name = "Alex Li"
 2 def change_name(name):
 3     print("before change:",name)
 4     name = "金角大王,一个有Tesla的男人"
 5     print("after change", name))
 6 change_name(name)
 7 print("在外面看看name改了么?",name)
 8 执行结果:
 9 before change: Alex Li
10 after change 金角大王,一个有Tesla的男人
11 在外面看看name改了么? Alex Li

  全局与局部变量

  在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量。
  全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序。
  当全局变量与局部变量同名时:
  在定义局部变量的子程序内,局部变量起作用;在其它地方全局变量起作用。

  6、递归函数

  在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。

 1 def calc(n):
 2     print(n)
 3     if int(n/2) ==0:
 4         return n
 5     return calc(int(n/2))
 6 calc(10)
 7 输出:
 8 10
 9 5
10 2
11 1

  递归特性:

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

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

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

  7、高阶函数

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

1 def add(x,y,f):
2     return f(x) + f(y)
3  
4 res = add(3,-6,abs)
5 print(res)

 

posted @ 2016-08-12 11:21  有位青年  阅读(349)  评论(0编辑  收藏  举报