py_chunwei

导航

Python之旅Day3 文件操作 函数(递归|匿名|嵌套|高阶)函数式编程 内置方法

知识回顾

常见五大数据类型分类小结:数字、字符串、列表、元组、字典

  按存值个数区分:容器类型(列表、字典、元组)

          标量原子(数字、字符串)

  按是否可变区分:可变(列表、字典)

          不可变(数字、字符串、元组)

  按访问顺序区分:直接访问(数字)

          顺序访问(字符串、列表、元组)

          key值访问(字典)

1. 集合

  主要作用:

  1)去重

  2)关系测试:交集、差集、并集、反向差集等

2. 元组

  元组是一个自读列表,只有count和index这2个方法

  例如:如果一些数据不想被人修改,可以存成元组,比如身份证列表

3. 字典

  key-value对类型

  特性:无序、去重、查询速度比列表快(比列表暂用内存多)

4. 字符编码

  Python2.X里默认字符编码为ascii,Python3.X里默认编码为utf-8

C:\Users\Administrator>python2
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit
AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>>

C:\Users\Administrator>python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>>

  编码应用比较多的场景当属爬虫,  在Python2.X中,写中文需要加“#-*-coding:utf-8 -*-” 

  utf-8转gbk:utf8线decode(解码)成Unicode,再encode(编码)成gbk

  常见转码图示:

  *所有的程序在内存里默认都是unicode

 

 

文件操作

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

  open文件时,encoding不声明的话,默认使用操作系统的编码来解释文件

  现有如下文件:

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
我曾千万次梦见
The splendid things I planned
那些我计划的绚丽蓝图
I always built to last on weak and shifting sand
但我总是将之建筑在易逝的流沙上
现有文件

  基本操作

###操作编码###
f = open('file',encoding='utf-8')   #打开文件
first_line = f.readline()   #得到文件句柄后赋值一个变量
print('first line:',first_line)   #读文件的第一行
print('万能分割线'.center(30,'-'))   #自定义输出一个分割提示
data = f.read()   #读取源文件剩余内容(大文件时勿用)
print(data)   #打印文件

f.close()   #关闭文件


###运行结果###
C:\Python35\python.exe D:/Python代码目录/day3/file操作.py
first line: 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
我曾千万次梦见
The splendid things I planned
那些我计划的绚丽蓝图
I always built to last on weak and shifting sand
但我总是将之建筑在易逝的流沙上

Process finished with exit code 0

  常见文件打开模式

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

"+" 表示可以同时读写某个文件 r+,可读写文件,可以定长修改,(从文件开头)【可读;可写;可追加】 w+,写读(清空原文件,再写入新内容) a+,追加+读(从文件结尾

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用) rU r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注) rb wb ab

  其他操作

#close   关闭
#isstty   判断是不是终端(返回Ture或False)
#readable   判断文件是不是可读
#readall   读所有
#seekable   是不是可寻
#tell   光标
#truncate(100)   是否可以截断(只能从头截断)
#flush   类似于强制直接写到硬盘(打印实时日志)

  with语句

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

    with open('log','r') as f:   
    ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。 在Python
2.7 后,with又支持同时对多个文件的上下文进行管理
即: with open(
'log1') as obj1, open('log2') as obj2: pass

 

函数

 函数的定义

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

 函数的特性

  1)减少重复代码

  2)使程序变得可扩展

  3)使程序变得易维护

 语法定义 

###语法实例###
def hi(): #定义函数名hi
    print("Hello, nice to meet you!")
hi()  #调用该函数

###执行结果###
C:\Python35\python.exe D:/Python代码目录/day3/file操作.py
Hello, nice to meet you!

Process finished with exit code 0

 

函数参数与局部变量

  参数:形参与实参

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

  2)实参变量:有确定值的参数,可以是常量、变量、表达式、函数等所有的数据类型。因此应预先用赋值、输入等办法使参数获得确定值

#下面这段代码
a,b = 2,4
c1 = a**b
print("c1= ",c1)


#改成用函数写
def calc(x,y):   #x,y在此为形参
    res = x**y
    return res #返回函数执行结果

c2 = calc(a,b) #结果赋值给c变量  a,b为实参
print("c2= ",c2)

 

默认参数

##平常写法##
def stu_info(name,age,country,course):  
    print("----注册学生信息------")
    print("姓名:",name)
    print("age:",age)
    print("国籍:",country)
    print("课程:",course)

stu_info("王五",22,"CN","python_devops")
stu_info("张三",21,"CN","linux")
stu_info("李四",25,"CN","linux")

##运行结果##

C:\Python35\python.exe D:/Python代码目录/day3/函数.py
----注册学生信息------
姓名: 王五
age: 22
国籍: CN
课程: python_devops
----注册学生信息------
姓名: 张三
age: 21
国籍: CN
课程: linux
----注册学生信息------
姓名: 李四
age: 25
国籍: CN
课程: linux

Process finished with exit code 0


发现 country 这个参数 基本都 是"CN", 就像我们在网站上注册用户,像国籍这种信息,你不填写,默认就会是 中国, 这就是通过默认参数实现的,把country变成默认参数非常简单
#def stu_info(name,age,country="CN",course):  ##country="USA"位置应放在最后,否则报错
def stu_info(name,age,course,country="CN"):
    print("----注册学生信息------")
    print("姓名:",name)
    print("age:",age)
    print("国籍:",country)
    print("课程:",course)

stu_info("王五",22,"python_devops") #默认会赋值CN
stu_info("张三",21,"linux",country="USA")
#stu_info("赵六",22,country="USA","python_devops") ##country="USA"位置应放在最后,否则报错
stu_info("李四",25,"CN","linux")

##运行结果##
C:\Python35\python.exe D:/Python代码目录/day3/函数.py
----注册学生信息------
姓名: 王五
age: 22
国籍: CN
课程: python_devops
----注册学生信息------
姓名: 张三
age: 21
国籍: USA
课程: linux
----注册学生信息------
姓名: 李四
age: 25
国籍: linux
课程: CN

Process finished with exit code 0

*正常情况下,给函数传参数要按顺序,不想按顺序就可以用关键参数,只需指定参数名即可,但记住一个要求就是,关键参数必须放在位置参数之后。
  def stu_info(name,age,course,country="CN")
  stu_info("张三",21,"linux",country="USA")

 

非固定参数*args和**kwargs

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

  *agrs默认传入的数据类型为元组

##非固定参数##
def stu_info(name,age,*args): # *args 会把多传入的参数变成一个元组形式
    print(name,age,args)

stu_info("WeiGe",22) #WeiGe 22 () #后面这个()就是args,只是因为没传值,所以为空

stu_info("Jack",32,"CN","Python","hobbits is python")  #此处args的赋值为"CN","Python","hobbits is python"

##输出##
C:\Python35\python.exe D:/Python代码目录/day3/函数.py
WeiGe 22 ()
Jack 32 ('CN', 'Python', 'hobbits is python')

Process finished with exit code 0

  *kwagrs默认传入的数据类型为字典

def stu_info(name,age,*args,**kwargs): # *kwargs 会把多传入的参数变成一个dict形式
    print(name,age,args,kwargs)

stu_info("WeiGe",22)#WeiGe 22 () {}#后面这个{}就是kwargs,只是因为没传值,所以会显示为空

stu_info("WeiGe",32,"CN","Python",sex="Male",province="WuHan")# ()和{}分别都赋值

##输出##
C:\Python35\python.exe D:/Python代码目录/day3/函数.py
WeiGe 22 () {}
WeiGe 32 ('CN', 'Python') {'province': 'WuHan', 'sex': 'Male'}

Process finished with exit code 0

  函数参数小结:

  1)*args,**kwargs   *和**是标准格式,后面的字母可以自己定义,但不建议对其做修改

  2)参数的顺序;位置参数按顺序,默认参数必须放在位置参数后面,关键参数也必须放在位置参数的后面,非固定参数在末尾

 

全局与局部变量

###全局与局部变量###
login_status = False #全局变量 def auth(): user =input("username:").strip() passwd=input("passwd:").strip() _username="weige" _password="211985" if user==_username and passwd==_password: print("passed authentication! ") global login_status #可以使下面的局部变量在全局可用 login_status=True #局部变量 def home(): if login_status == True: # global login_status 之后,auth中验证账号和密码之后,当home及pay调用时,则无需在验证 print("welecome to home page!") else: auth() def pay(): if login_status == True: print("welcome to pay page!") else: auth() auth() home() pay() ##运行结果## C:\Python35\python.exe D:/Python代码目录/day3/函数.py username:weige passwd:211985 passed authentication! welecome to home page! welcome to pay page! Process finished with exit code 0

 

返回值

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

###将全局变量的方式改为用返回值的方式###
def auth():
    user =input("username:").strip()
    passwd=input("passwd:").strip()

    _username="weige"
    _password="211985"
    if user==_username and passwd==_password:
        print("passed authentication! ")
        return True  #认证成功返回True
    else:
        return False  #认证失败返回False

def home():
    if login_status == True:
        print("welecome to home page!")
    else:
        auth()

def pay():
    if login_status == True:
        print("welcome to pay page!")
    else:
        auth()

login_status = auth()
home()
pay()


##执行结果##
C:\Python35\python.exe D:/Python代码目录/day3/函数.py
username:weige
passwd:211985
passed authentication! 
welecome to home page!
welcome to pay page!

Process finished with exit code 0


说明:
    1.一旦函数经过调用并开始执行,那你的函数外部的程序,就没有办法再控制函数的执行过程了,此时外部程序只有安静的等待函数的执行结果,为啥要等待函数的执行结果?因为外部程序要根据函数的执行结果来判断下一步怎么走,这个执行结果就是以return的形式返回给外部程序)
    2.return代表着一个函数的结束
    3.return的可以返回任意数据类型
    4.对于用户角度,数可以返回任意数量的值,py本身来说,函数只能返回一个值

 

函数的前向引用之“函数即变量”

  1)未定义直接使用(报错)

  2)正常流程,先定义后使用(不报错)

  3)先使用后定义(把函数达成了变量)

#会报错
def action():
    print('in the action')
    logger()
action()
'''运行结果:
NameError: name 'logger' is not defined
'''

#正常先定义后引用(不报错)
def logger():
    print('in the logger')
def action():
    print('in the action')
    logger()
action()
'''运行结果:
in the action
in the logger

'''

#先用后定义,把函数当成了变量(不报错)
def action():
    print('in the action')
    logger()
def logger():
    print('in the logger')
action()
'''运行结果:
in the action
in the logger

'''

 

嵌套函数

  嵌套函数顾名思义就是函数里面套用函数 

###嵌套函数###

#嵌套定义
name = "Weige"

def change_name():
    name = "Weige2"

    def change_name2():
        name = "Weige3"
        print("第3层打印",name)

    change_name2() #调用内层函数
    print("第2层打印",name)


change_name()
print("最外层打印",name)


###运行结果###
C:\Python35\python.exe D:/Python代码目录/day3/函数.py
第3层打印 Weige3
第2层打印 Weige2
最外层打印 Weige

Process finished with exit code 0


#嵌套调用
def my_max4(w,x,y,z):
    res1=my_max2(w,x)
    res2=my_max2(res1,y)
    res3=my_max2(res2,z)
    return res3

def my_max2(m,n):
    if m>n:
        return m
    else:return n
'''
#三元运算的方式
def my_max2(m,n):
    res=m if m>n else n
    return res
'''

print(my_max4(10,20,-5,8))

 

归函数

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

##递归函数##
def calc(n):
    if n//2 >0:
        calc(n//2)
    print(n)

calc(20)

##运行结果##
C:\Python35\python.exe D:/Python代码目录/day3/函数.py
1
2
5
10
20

Process finished with exit code 0

递归特性:
1. 必须有一个明确的结束条件
2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少
3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)

  递归应用-二叉算法

##应用方法1##
data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]
 
def binary_search(dataset,find_num):
    print(dataset)
 
    if len(dataset) >1:
        mid = int(len(dataset)/2)
        if dataset[mid] == find_num:  #find it
            print("找到数字",dataset[mid])
        elif dataset[mid] > find_num :# 找的数在mid左面
            print("\033[31;1m找的数在mid[%s]左面\033[0m" % dataset[mid])
            return binary_search(dataset[0:mid], find_num)
        else:# 找的数在mid右面
            print("\033[32;1m找的数在mid[%s]右面\033[0m" % dataset[mid])
            return binary_search(dataset[mid+1:],find_num)
    else:
        if dataset[0] == find_num:  #find it
            print("找到数字啦",dataset[0])
        else:
            print("没的分了,要找的数字[%s]不在列表里" % find_num)
 
 
binary_search(data,16)

##结果##
C:\Python35\python.exe D:/Python代码目录/day3/二分查找.py
[1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]
找的数在mid[18]左面
[1, 3, 6, 7, 9, 12, 14, 16, 17]
找的数在mid[9]右面
[12, 14, 16, 17]
找到数字 16

Process finished with exit code 0



##应用方法2##
date = range(1,42000000)
def binary_seach(find_str,data_set,count):
    mid = int(len(data_set)/2)
    if mid==0:
        if data_set[mid] == find_str:
            print("find it finally",find_str,count)
        else:
            print("cannot find this num in list",find_str,count)
        return
    if data_set[mid] == find_str:
        print("find it",find_str,mid)
    elif data_set[mid] > find_str:
        print("going ti secrch in left",data_set[mid],data_set[0:mid])
        binary_seach(find_str,data_set[0:mid],count+1)
    else:
        print("going to search in right",data_set[mid],data_set[mid+1:])
        binary_seach(find_str,data_set[mid+1:],count+1)
binary_seach(132342,date,0)

##运行结果##
C:\Python35\python.exe D:/Python代码目录/day3/二分查找.py
going ti secrch in left 21000000 range(1, 21000000)
going ti secrch in left 10500000 range(1, 10500000)
going ti secrch in left 5250000 range(1, 5250000)
going ti secrch in left 2625000 range(1, 2625000)
going ti secrch in left 1312500 range(1, 1312500)
going ti secrch in left 656250 range(1, 656250)
going ti secrch in left 328125 range(1, 328125)
going ti secrch in left 164063 range(1, 164063)
going to search in right 82032 range(82033, 164063)
going to search in right 123048 range(123049, 164063)
going ti secrch in left 143556 range(123049, 143556)
going ti secrch in left 133302 range(123049, 133302)
going to search in right 128175 range(128176, 133302)
going to search in right 130739 range(130740, 133302)
going to search in right 132021 range(132022, 133302)
going ti secrch in left 132662 range(132022, 132662)
find it 132342 320

Process finished with exit code 0

 

匿名函数

  匿名函数就是不许要显式的函数(lambda)

##常规写法##
#def calc(m):   #赋一个参数常规写法
def calc(m,n):  #赋值多个参数
    #return m*m
    return m*n
#print(calc(6))
print(calc(6,9))


##lambda匿名函数写法##
calc2 =lambda x:x*x
#calc2 =lambda x,y:x*y  #赋值过个参数

print(calc2(6))
#print(calc2(6,9))


运行结果
C:\Python34\python.exe E:/Python16/day4/匿名函数.py
54
36

Process finished with exit code 0

*匿名函数只能加一般参数,不能接关键参数等


##匿名函数和三元运算##
def calc(n):
    return -n

data = map(lambda n: n*2 if n>5 else n,range(10))

for i in data:
    print(i)

##运行结果##
C:\Python34\python.exe E:/Python16/day4/匿名函数.py
0
1
2
3
4
5
12
14
16
18

Process finished with exit code 0

 

高阶函数

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

##高阶函数##
def add(x, y, f): #add用来算绝对值
    return f(x) + f(y)


res = add(3, -6, abs) #|3| + |-6|的结果
print(res)

##运行结果##
C:\Python34\python.exe E:/Python16/day4/匿名函数.py
9

Process finished with exit code 0

 

函数式编程

  "函数式编程"中的函数不是计算机中的函数(def),而是指数学中的函数,即自变量的映射。也就是一个函数的值取决于函数参数的值,不依赖其他状态。比如sqrt(x)函数计算x的平方根,只要x不变,不论什么时候调用,调用几次,值都是不变的。

  Python对函数式编程提供部分支持。由于Python允许使用变量,因此,Python不是纯函数式编程语言。

"函数式编程"是一种"编程范式"(programming paradigm),也就是如何编写程序的方法论。

主要思想是把运算过程尽量写成一系列嵌套的函数调用。举例来说,现在有这样一个数学表达式:

  (1 + 2) * 3 - 4

传统的过程式编程,可能这样写:

  var a = 1 + 2;

  var b = a * 3;

  var c = b - 4;

函数式编程要求使用函数,我们可以把运算过程定义为不同的函数,然后写成下面这样:

  var result = subtract(multiply(add(1,2), 3), 4);
    #add ==加
    #multiply ==乘
    #subtract ==减
    #abs    ==绝对值


这段代码再演进以下,可以变成这样

  add(1,2).multiply(3).subtract(4)

这基本就是自然语言的表达了。再看下面的代码,大家应该一眼就能明白它的意思吧:

merge([1,2],[3,4]).sort().search("2")


######函数式第一类对象######
    函数式第一类对象:就是函数可以被当做数据来传递

def func():
    print('in the func')

#被引用
f1=func
f1()

#可作为参数
def foo(x):
    x()
foo(func)

#返回值可以是函数
def foo():
    return func
res=foo()
res()

#可以作为容器类型的元素
func_dic={
    'func':func
}
func_dic['func']()

 

函数的内置方法

 

 

#abs:取绝对值
>>> abs(0)
>>> abs(-3)
>>> abs(2)

#all:判断列表里的数是不是为真(全为真才返回True)
>>> a=[1,2,3]
>>> all(a)
True

#any:判断列表里的数是不是为真(就要有一个为真就返回True)
>>> a=[0,2,-3]
>>> any(a)
True
>>> a=[0]
>>> any(a)
False
>>> a=([])  #列表为空则为假
>>> any(a)
False

#bin:把数字转为二进制
>>> print(bin(10))
0b1010

bool:判断布尔值(True False)

#callable:判断对象是否可以调用
def sayhi():
    pass
name = "weige"
print(callable(sayhi))
print(callable(name))
C:\Python34\python.exe E:/Python16/day4/内置函数.py
True
False
Process finished with exit code 0

#chr:打印对应的ascii值
print(chr(97))
print(chr(98))
print(chr(117))
C:\Python34\python.exe E:/Python16/day4/内置函数.py
a
b
u
Process finished with exit code 0

#ord:将ascii转为对应的数字
print(ord('a'))
print(ord('b'))
print(ord('u'))
C:\Python34\python.exe E:/Python16/day4/内置函数.py
Process finished with exit code 0

#exec:将字符串的内容当方法执行
  >>> a = "print('hello world')"
  >>> a
  "print('hello world')"
  >>>
  >>> exec(a)
  hello world
  >>>
#compile: 在其他地方调用一个py文件(与import功能类似)
f = open("hello.py",encoding="utf-8")
code = compile(f.read(),'','exec')
print(code)
exec(code)
C:\Python34\python.exe E:/Python16/day4/内置函数.py
<code object <module> at 0x00000000021C7D20, file "", line 1>
hello
你好
Process finished with exit code 0

#eval:计算
>>> eval("4*2")
>>> eval("4*4/2")
8.0
>>> eval("4*3/2")
6.0
'''
可以把list,tuple,dict和string相互转化。
#################################################
字符串转换成列表
>>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>>type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> type(b)
<type 'list'>
#################################################
字符串转换成字典
>>> a = "{1: 'a', 2: 'b'}"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
{1: 'a', 2: 'b'}
>>> type(b)
<type 'dict'>
#################################################
字符串转换成元组
>>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
>>> type(b)
<type 'tuple'>
'''


#complex:复数

#dict:生产字典

#dir:查看对象有哪些方法可用
def hello(a):
    pass
print(dir(hello))
C:\Python34\python.exe E:/Python16/day4/内置函数.py
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Process finished with exit code 0

#divmod:求商和余数
print(divmod(10,2))
print(divmod(5,3))
C:\Python34\python.exe E:/Python16/day4/内置函数.py
(5, 0)
(1, 2)
Process finished with exit code 0

#filter:过滤
for i in filter(lambda x:x>5,range(10)):#过滤出x大于5的数字
    print(i)
C:\Python34\python.exe E:/Python16/day4/内置函数.py
9
Process finished with exit code 0

#float:浮点数

#format:字符串格式化

# frozenset:把集合变成只读的
a = frozenset({1,7,2,3,4})
b = {1,7,2,3,4}
print(dir(a))
print(dir(b))
C:\Python34\python.exe E:/Python16/day4/内置函数.py
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
Process finished with exit code 0

#globals:把当前程序所在内存里的所有数据都以字典的形式打印出来
print(globals())

#id:查看内存地址

#isinstance:判断对象是否为已知类型;
  语法:isinstance(project,type)
  实例:
    >>> a = 4
    >>> isinstance (a,int)
    True
    >>> isinstance (a,str)
    False
    >>> isinstance (a,(str,int,list))
    True

    >>> a = "b"
    >>> isinstance(a,str)
    True
    >>> isinstance(a,int)
    False
    >>> isinstance(a,(int,list,float))
    False
    >>> isinstance(a,(int,list,float,str))
    True

#issubclass:判断是不是一个子类

#max:求一个最大值

#hex:十六进制

#oct:八进制


#hash返回对象的哈希值
>>> hash('wuchunwei')
>>> 1==1.0==1.00000
True
>>>
>>> hash(1)
>>> hash(1.0)
>>> hash(1.00000)
>>>

#repr:将对象转为字符串
#reversed:反转
#round:四舍五入(默认不保留)
>>> round(1.24618)
>>> round(1.54618)
>>> round(1.54618,3)
1.546
>>>

#slice:列表切片的方法(解释器它自己用)

#pow: 求幂(求平方)
print(pow(2,4))
print(pow(8,2))
C:\Python34\python.exe E:/Python16/day4/内置函数.py
Process finished with exit code 0

#print:打印
msg = "hello world"
f = open("tofile","w")
print(msg,"welcome to here",sep="|",end="=",file=f) #sep指定连接符,end指定结束符
#当前路径下生成了一个名为tofile的文件,内容如下(file = f)
hello world|welcome to here=

#set:生成集合
data = [1,2,3,5,3,7,0]
print(set(data))
C:\Python34\python.exe E:/Python16/day4/内置函数.py
{0, 1, 2, 3, 5, 7}
Process finished with exit code 0

#zip: 合并成元组
a = [-5,1,3,5,7,9]
b = [2,4,6,8]
for i in zip(a,b):
    print(i)
C:\Python34\python.exe E:/Python16/day4/内置函数.py
(-5, 2)
(1, 4)
(3, 6)
(5, 8)
Process finished with exit code 0

#sorted()函数就可以对list进行排序
    >>> sorted([36, 5, -12, 9, -21])
    [-21, -12, 5, 9, 36]
  #此外,sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序:
    >>> sorted([36, 5, -12, 9, -21], key=abs)
    [5, 9, -12, -21, 36]
  #key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序。对比原始的list和经过key=abs处理过的list:
    list = [36, 5, -12, 9, -21]
    keys = [36, 5,  12, 9,  21]
  #然后sorted()函数按照keys进行排序,并按照对应关系返回list相应的元素:

  keys排序结果 => [5, 9,  12,  21, 36]
                |  |    |    |   |
  最终结果     => [5, 9, -12, -21, 36]

  我们再看一个字符串排序的例子:
    >>> sorted(['bob', 'about', 'Zoo', 'Credit'])
    ['Credit', 'Zoo', 'about', 'bob']
  #默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面。

  #现在,我们提出排序应该忽略大小写,按照字母序排序。要实现这个算法,不必对现有代码大加改动,只要我们能用一个key函数把字符串映射为忽略大小写排序即可。忽略大小写来比较两个字符串,实际上就是先把字符串都变成大写(或者都变成小写),再比较。

  这样,我们给sorted传入key函数,即可实现忽略大小写的排序:
    >>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
    ['about', 'bob', 'Credit', 'Zoo']
  要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True:
    >>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
    ['Zoo', 'Credit', 'bob', 'about']

 

posted on 2017-02-08 15:42  py_chunwei  阅读(327)  评论(0编辑  收藏  举报