python学习笔记-(七)python基础--集合、文件操作&函数

本节内容

1.集合操作

2.文件操作

3.字符编码与转码

4.函数操作


1.集合操作

集合是一个无序的、不重复的数据组合;

1.1 常用操作

它的作用是:

1)自动去重:列表变成集合,自动去重;

>>> list_1 = [1,4,4,5,6,7,9,10]
>>> list_1 =set(list_1)
>>> print(list_1)
{1, 4, 5, 6, 7, 9, 10} 

2)关系测试:测试两组数据之间的关系,交集、并集、差集、对称差集、父集、子集等

#交集 intersection          &
>>> list_1 = set([1,4,4,5,6,7,9,10])
>>> list_2 = set([2,45,6,11])
>>> print(list_1.intersection(list_2)) #list_1和list_2的交集
{6}
>>> print(list_1 & list_2)
{6}
#并集 union    |
>>> list_1 = set([1,4,4,5,6,7,9,10])
>>> list_2 = set([2,45,6,11])
>>> print(list_1.union(list_2))
{1, 2, 4, 5, 6, 7, 9, 10, 11, 45}
>>> print(list_1 | list_2)
{1, 2, 4, 5, 6, 7, 9, 10, 11, 45}
#差集 in list_1 but not in list_2   ----difference
>>> list_1 = set([1,4,4,5,6,7,9,10])
>>> list_2 = set([2,45,6,11])
>>> print(list_1.difference(list_2))
{1, 4, 5, 7, 9, 10}
>>> print(list_1 - list_2)
{1, 4, 5, 7, 9, 10}
#对称差集 symmetric_difference ----去掉两者相同的数据后合并
>>> list_1 = set([1,4,4,5,6,7,9,10])
>>> list_2 = set([2,45,6,11])
>>> print(list_1.symmetric_difference(list_2))
{1, 2, 4, 5, 7, 9, 10, 11, 45}
>>> print(list_1 ^ list_2)
{1, 2, 4, 5, 7, 9, 10, 11, 45}
#子集 issubset
>>> list_1 = set([1,2,3,4,5,6])
>>> list_2 = set([1,4])
>>> print(list_1.issubset(list_2))
False
>>> print(list_2.issubset(list_1))
True
#父集 issuperset
>>> list_1 = set([1,2,3,4,5,6])
>>> list_2 = set([1,4])
>>> print(list_1.issuperset(list_2))
True
>>> print(list_2.issuperset(list_1))
False
#没有交集则为true,有交集为false
>>> list_1 = set([1,2,3,4,5,6])
>>> list_2 = set([1,4])
>>> print(list_1.isdisjoint(list_2))
false

1.2 基本操作

  • 添加
#添加一项
>>> list1 = set([1,3,4,6,7])
>>> list1.add(10)
>>> print(list1)
{1, 3, 4, 6, 7, 10}
#添加多项
>>> list1 = set([1,2])
>>> list1.update([6,8,10])
{8, 1, 2, 10, 6}
  • 删除
#remove ---删除不存在的元素会报错
>>> list1 = set([1,2,6,8,10])
>>> list1.remove(2)
>>> print(list1)
{8, 1, 10, 6}
>>> list1.remove(11)
>>> print(list1)
Traceback (most recent call last):
  File "C:/Users/Administrator/PycharmProjects/cc/day3/set_test.py", line 2, in <module>
    list1.remove(11)
KeyError: 11
#discard ---remove的友好版本,删除不存在的元素不会报错
>>> list1 = set([1,2,6,8,10])
>>> list1.discard(2)
>>> print(list1)
{8, 1, 10, 6}
>>> list1.discard(11)
>>> print(list1)
{8, 1, 2, 10, 6}
#pop ---随机删除
>>> list1 = set([1,2,6,8,10])
>>> list1.pop()
>>> print(list1)
{1, 2, 10, 6}  ---因集合是无序的,故随机删除某一项

2.文件操作

对文件操作流程:

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

2.1 打开文件

#文件句柄 = open('文件路径', '模式')

文件名:yesterday

Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戏弄生命 视其为愚蠢的游戏
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed

打开文件的模式有:

  • r ,只读模式【默认】
    >>> f = open("yesterday,'r',encoding="utf-8")
    >>> a = f.read()
    >>> print(a)
    >>> f.close()
    Somehow, it seems the love I knew was always the most destructive kind
    不知为何,我经历的爱情总是最具毁灭性的的那种
    Yesterday when I was young
    昨日当我年少轻狂
    The taste of life was sweet
    生命的滋味是甜的
    As rain upon my tongue
    就如舌尖上的雨露
    I teased at life as if it were a foolish game
    我戏弄生命 视其为愚蠢的游戏
    The way the evening breeze
    就如夜晚的微风
    May tease the candle flame
    逗弄蜡烛的火苗
    The thousand dreams I dreamed
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
    >>> f = open("1.txt",'w',encoding="utf-8")
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容;】
    >>> f = open("1.txt",'a',encoding="utf-8")

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

  • r+, 读写【可读,可写】
    >>> f = open("1.txt",'r+',encoding="utf-8")
  • w+,写读【可读,可写】
    >>> f = open("1.txt",'w+',encoding="utf-8")
  • a+, 写读【可读,可写】
    >>> f = open("1.txt",'a+',encoding="utf-8")

 "b"表示以字节的方式操作(跨平台、视频文件等使用)

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

2.2 操作文件

  • read()

read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。然而 read() 生成文件内容最直接的字符串表示,但对于连续的面向行的处理,它却是不必要的,并且如果文件大于可用内存,则不可能实现这种处理。

>>> f = open("yesterday,'r',encoding="utf-8")
>>> a = f.read()
>>> print(a)
>>> f.close()
Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戏弄生命 视其为愚蠢的游戏
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed
  • readlines()---适合读小文件

一次读取整个文件,象 read() 一样,readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理。

>>> f = open("yesterday","r",encoding="utf-8")#文件句柄
>>> for index,line in enumerate(f.readlines()):
>>>     if index == 9:
>>>         print('---我是分割线---')
>>>         continue
>>>     print(line.strip())
>>> f.close()
Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
---我是分割线---
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed
  • readline() 

 readline() 每次只读取一行

>>> f = open("yesterday","r",encoding="utf-8")#文件句柄
>>> a = f.readline()
>>> print(a)
>>> f.close()
Somehow, it seems the love I knew was always the most destructive kind
  • 高效读取文件方法
>>> f = open("yesterday","r",encoding="utf-8")#文件句柄
>>> for line in f:
>>>      print(line.strip())
>>> f.close()
Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戏弄生命 视其为愚蠢的游戏
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed

2.3 管理上下文--with语句

上面我们可以看到,每次打开后都需要关闭文件,十分繁琐。。。

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

>>> with  open("yesterday","r",encoding="utf-8") as f:
>>>     .....

2.4 其他扩展

#告知当前光标的位置
>>> f = open('yesterday','r',encoding='utf-8')
>>> print(f.tell())
0
#光标回到首位
>>> f.seek(0)
#判断是否可移动 
>>> f.seekable
#判断文件是否可读
>>> f.readable()
#判断文件是否可写
>>> f.writable()
#文件描述符
f.flieno()

3.字符编码与转码

详细文章:http://www.cnblogs.com/luotianshuai/articles/5735051.html 

Python3.0中默认的编码类型就是Unicode

encode:字符编码

decode:字符解码

Q:为什么要用到字符编码和解码?

A:有些文档可能采用的是某种编码方式(如utf-8)来存储文本,但如果我们展现的工具是另外一种编码方式(如gb2312),若我们不做些转码的工作,那么在此工具中显示的将会是乱码。

4. 函数操作

4.1 函数基本语法及特性

定义:

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

函数能提高应用的模块性,和代码的重复利用率。

特性:

  1. 减少重复代码

  2. 使程序变的可扩展

  3. 使程序变得易维护

函数定义规则:

你可以定义一个由自己想要功能的函数,这被叫做用户自定义函数。以下是简单的规则: 

  • 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()。
  • 任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。
  • 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
  • 函数内容以冒号起始,并且缩进。
  • return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。
def 函数名(参数):
    ...
    函数体
    ...
    返回值

4.2 函数调用

4.2.1 调用方法:

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

# x为函数的参数
>>> def num(x):
...  print(x)
...
# 123456等于x
>>> num("123")
123 

4.2.2 参数

4.2.2.1 形参和实参

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

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

区别:

形参是虚拟的,不占用内存空间,形参变量只有在被调用时才分配内存单元;

实参是一个变量,占用内存空间;

数据传送单向,实参传给形参,不能形参传给实参。 

4.2.2.2 位置参数和关键字参数

  • 位置参数:

传入参数的值按照顺序依次赋值(与形参一一对应)

def func_2(x,y):
    print(x)
    print(y)
    return
func_2(2,1)
#打印2,1


#超出或不足则报错
def func_2(x,y):
    print(x)
    print(y)
    return
func_2(2,1,3)
#TypeError: func_2() takes 2 positional arguments but 3 were given
  • 关键字参数:

关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。

使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。

1)关键字参数与形参顺序无关;

2)关键字参数不能写在位置参数前面;

>>> def func_2(x,y):
    print(x)
    print(y)
    return
func_2(x=2,1)

#SyntaxError: positional argument follows keyword argument

>>> def func_2(x,y):
    print(x)
    print(y)
    return
func_2(2,y=1)

4.2.2.3 默认参数

如果我们在创建函数的时候给函数定义了值,那么在调用函数的时候如果不填写值程序就会报错:

def func_2(x):
    print(x)
    return
func_2()

如果要解决这个问题就可以给函数的值指定一个默认值,指定函数的默认值需要在def这一行指定,制定之后,当调用这个函数的时候就不需要输入函数值了。

def func_2(x=1):
    print(x)
    return
func_2()

PS:有多个参数时,记得遵循以上原则,关键字参数不能放在位置参数前

4.2.2.4 参数组

  • 位置参数转换成元组存放(*args)
def func_2(*args):
    print(args)
    return
func_2(*[1,2,3,4,6])
  • 关键字参数转换成字典存放(**keyargs)
def func_2(**keyargs):
    print(keyargs)
    return
func_2(name = 'cc',age = 18)
#打印结果:{'age': 18, 'name': 'cc'}

 4.2.3 局部变量与全局变量

定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。

局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。

当全局变量与局部变量同名时:在定义局部变量的子程序内,局部变量起作用;在其它地方全局变量起作用。

total = 0;
def sum(x,y):
    '''返回两个参数的值'''
    total = x+y;
    print("函数内是局部变量:%s" % total)
sum(4,10)
print("函数外是全局变量:%s" % total)

#函数内是局部变量:14
#函数外是全局变量:0

4.3 返回值

函数的返回值需要使用到return这个关键字,返回值主要是用来接受函数的执行结果。

函数return后面是什么值,re就返回什么值,如果没有指定return返回值,那么会返回一个默认的参数None

在函数中,当return执行完成之后,return后面的代码是不会被执行的。---也可以理解为return就是函数的结束。

4.4 递归

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

递归特性:

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

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

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

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

4.5 匿名函数

传入函数参数不需要显式定义函数,可以用lambda x:statement (x为参数,statement为对参数执行的语句);

4.5.1 为什么要用匿名函数?

  • 程序一次行使用,所以不需要定义函数名,节省内存中变量定义空间
  • 可让程序更加简洁

4.5.2 匿名函数的规则:

  • 一般也就一行表达式,必须有返回值;
  • 不能有return;
  • 可以没有参数,也可有一个或多个参数;

4.5.3 匿名函数的用法:

lambda一般应用于函数式编程,代码简洁,常和reduce,filter等函数结合使用。

  • 无参数匿名:
>>> a = lambda : True #分号前无任何参数
>>> a()
True

等价于下面的def定义的函数
>>> def func(): return True
>>> func()
True
  • 带参数匿名:
>>> lambda x: x**3 #一个参数
>>> lambda x,y,z:x+y+z #多个参数
>>> lambda x,y=3: x*y #允许参数存在默认值
  • 匿名参数调用:

1)直接赋值给一个变量,然后再像一般函数调用

>>> c = lambda x,y,z: x*y*z
>>> c(2,3,4)
24
>>> c = lambda x,y=2: x+y #使用了默认值
>>> c(10) #不输的话,使用默认值2
12
>>> a = lambda *z:z #*z返回的是一个元祖
>>> a('Testing1','Testing2')
('Testing1', 'Testing2')
>>> c = lambda **Arg: Arg #arg返回的是一个字典
>>> c()
{}

2)直接后面传递实参

>>> print((lambda x,y: x if x> y else y)(101,102))
102 

#lambda返回的值,结合map,filter,reduce使用(map、filter、reduce用法见下面)
>>> print(list(filter(lambda x:x%3==0,[1,2,3,4,5,6])))
[3, 6] 等价于下面的列表推导式: >>> l = [x for x in [1,2,3,4,5,6] if x%3==0] >>> l [3, 6]

3)嵌套使用

lambda嵌套到普通函数中,lambda函数本身做为return的值

>>> def increment(n):
... return lambda x: x+n
...
>>> f=increment(4)
>>> f(2)
6

4.6 高阶函数

见下篇文章

原文地址:https://www.cnblogs.com/cocc/p/5746311.html