Python学习第三天

一、集合

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

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

常用操作:

 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”的一个浅复制

二、文件

对文件操作流程

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

基本操作:

 f = open('lyrics') #打开文件
first_line = f.readline()
print('first line:',first_line) #读一行
print('我是分隔线'.center(50,'-'))
data = f.read()# 读取剩下的所有内容,文件大时不要用
print(data) #打印文件 f.close() #关闭文件

打开文件的模式有:

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

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

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

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

  • rU
  • r+U

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

  • rb
  • wb
  • ab

其它语法

 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

三、字符编码与转码

需知:

1.在python2默认编码是ASCII, python3里默认是unicode

2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间

3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

 import sys
print(sys.getdefaultencoding()) msg = "我爱北京天安门"
#msg_gb2312 = msg.decode("utf-8").encode("gb2312")
msg_gb2312 = msg.encode("gb2312") #默认就是unicode,不用再decode,喜大普奔
gb2312_to_unicode = msg_gb2312.decode("gb2312")
gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8") print(msg)
print(msg_gb2312)
print(gb2312_to_unicode)
print(gb2312_to_utf8) in python3

四、函数

1、函数基本语法及特性

特性:

  1. 减少重复代码
  2. 使程序变的可扩展
  3. 使程序变得易维护

语法定义

 def sayhi():#函数名
print("Hello, I'm nobody!") sayhi() #调用函数

可以带参数

 #下面这段代码
a,b = 5,8
c = a**b
print(c) #改成用函数写
def calc(x,y):
res = x**y
return res #返回函数执行结果 c = calc(a,b) #结果赋值给c变量
print(c)

2、函数参数与局部变量

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

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

默认参数

 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"):

关键参数

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

非固定参数

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

 def stu_register(name,age,*args): # *args 会把多传入的参数变成一个元组形式
print(name,age,args) stu_register("Alex",22)
#输出
#Alex 22 () #后面这个()就是args,只是因为没传值,所以为空 stu_register("Jack",32,"CN","Python")
#输出
# Jack 32 ('CN', 'Python')
 def stu_register(name,age,*args,**kwargs): # *kwargs 会把多传入的参数变成一个dict形式
print(name,age,args,kwargs) stu_register("Alex",22)
#输出
#Alex 22 () {}#后面这个{}就是kwargs,只是因为没传值,所以为空 stu_register("Jack",32,"CN","Python",sex="Male",province="ShanDong")
#输出
# Jack 32 ('CN', 'Python') {'province': 'ShanDong', 'sex': 'Male'}

全局与局部变量

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

3、返回值

要想获取函数的执行结果,就可以用return语句把结果返回

注意:

  1. 函数在执行过程中只要遇到return语句,就会停止执行并返回结果,so 也可以理解为 return 语句代表着函数的结束
  2. 如果未在函数中指定return,那这个函数的返回值为None

4、递归

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

 def calc(n):
print(n)
if int(n/2) ==0:
return n
return calc(int(n/2)) calc(10) 输出:
10
5
2
1

递归特性:

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

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

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

5、高阶函数

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

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

Python学习笔记,day3的更多相关文章

  1. Python学习笔记——Day3

    Python字典(Dictionary) 字典是一种可变容器模型,可存储任意类型对象. 字典的每个键值(key => value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花 ...

  2. [python学习笔记]Day3

    函数 如: def is_leapyear(year): if (year%4 == 0 and year%100 != 0) or (year%400 == 0): return True else ...

  3. Python学习笔记 - day3 - 数据类型及运算符

    Python的数据类型 计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形.音频.视频.网页等各种各样的数据,不同 ...

  4. python学习笔记Day3

    set有点:1.访问速度快 2.天生解决了重复问题 tuple与set区别: 元组可重复,set不可重复创捷集合1 >>> s1.add('alex')>>> pr ...

  5. 【目录】Python学习笔记

    目录:Python学习笔记 目标:坚持每天学习,每周一篇博文 1. Python学习笔记 - day1 - 概述及安装 2.Python学习笔记 - day2 - PyCharm的基本使用 3.Pyt ...

  6. python学习笔记整理——字典

    python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...

  7. VS2013中Python学习笔记[Django Web的第一个网页]

    前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...

  8. python学习笔记之module && package

    个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...

  9. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  10. python学习笔记--Django入门四 管理站点--二

    接上一节  python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...

随机推荐

  1. Linux c codeblock的使用(三):使用函数库

    (一)概念 什么是函数库呢?一下子说概念大家可能不太熟悉,但是这实际上是大家在windows系统上经常见到的东西.没错,就是那些后缀为DLL的文件. linux上实际也有自己的函数库文件,文件类型为. ...

  2. 《用Python写爬虫》学习笔记(一)

    注:纯文本内容,代码独立另写,属于本人学习总结,无任何商业用途,在此分享,如有错误,还望指教. 1.为什么需要爬虫? 答:目前网络API未完全放开,所以需要网络爬虫知识. 2.爬虫的合法性? 答:爬虫 ...

  3. asp.net IHttpModule浅析

    在asp.net程序中,我们除了使用系统自带的HttpModule模块,还可以自己定义一些自己的HttpModule接口模块.一个asp.net程序可以接收多个HttpModule模块. 众所周知,a ...

  4. windows 10系统在右键中添加管理员打开cmd

    需要修改注册表内容,新建文件,后缀名改为reg,文件中粘贴下边的代码 Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\Directory ...

  5. FTP 代理服务器实现

    本文将在Linux环境下实现一个简单的FTP代理服务器,主要内容涉及FTP主动/被动模式和简单的Socket编程. 1. 主动模式和被动模式 FTP有两种模式,即主动模式(Active Mode)和被 ...

  6. 记录前台js判断,如果为空,給议空的占位

    这个主要是根据所有的值,按顺序输出,如果没有值,就给予空的占位, //页面加载的时候获取左边和右边的所有游客id       var array_left_start = new Array();   ...

  7. Mad Libs 游戏

    name1=input('请输入一个名字:') name2=input('再输入一个名字:') print('丑不拉几的{}被美丽的{}给迷得神魂颠倒'.format(name1,name2)) in ...

  8. nodejs03-GET数据处理

    数据请求:--- 前台:form ajax jsonp 后台:一样 请求方式: 1.GET 数据在URL中 2.POST 数据在请求体中 请求数据组成: 头--header:url,头信息 身子--c ...

  9. Qt代码

    ui->LoginPushButton->setStyleSheet(//正常状态样式 "QPushButton{" "background-color:rg ...

  10. input()和print()函数同时输入输出多个数据--python3

    使用input()和print()函数同时输入输出多个数据,需要空格分割输入信息 #!/usr/bin/python3#-*- conding:utf-8 -*- name, age, QQ = in ...