Python 内置函数、匿名函数

  截止到python版本3.6.2,现在python一共为我们提供了68个内置函数。它们就是python提供给你直接可以拿来使用的所有函数。

一,作用域相关(2个)

 基于字典的形式获取局部变量和全局变量

locals()  #返回本地作用域中的所有名字
globals() #返回全局作用域中的所有名字
类似的变量
global 变量 全局变量
nonlocal 变量 局部变量与离他近的上层函数相关

二,迭代器/生成器相关(3个)

  1, iter()

迭代器 = iter(可迭代的) #生成迭代器
迭代器 = 可迭代的.__iter__()

2 ,next()
迭代器.__next__()  #调用迭代器
next(迭代器)

3,range()
range(10)
range(1,11)
print('__next__' in dir(range(1,11,2)))

三,其他(12个)

 

(1)查看内置属性 1

       查看所有的内置函数

     dir(__builtins__) 

  查看某对象的属性及方法

     dir([1,2])

          dir(list)

 (2)和调用相关 1

  callable(o),o是参数,看这个变量是不是可调用。

  如果o是一个函数名,就会返回True

 (3)输入输出相关 2

  input()

  print()

def print(self, *args, sep=' ', end='
', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='
', file=sys.stdout, flush=False)
    file:  默认是输出到屏幕,如果设置为文件句柄,输出到文件
    sep:   打印多个值之间的分隔符,默认为空格
    end:   每一次打印的结尾,默认为换行符
    flush: 立即把内容输出到流文件,不作缓存
    """
View Code
import time
for i in range(0,101,2):  
     time.sleep(0.1)
     char_num = i//2      #打印多少个'*'
     per_str = '
%s%% : %s
' % (i, '*' * char_num) if i == 100 else '
%s%% : %s'%(i,'*'*char_num)
     print(per_str,end='', flush=True)
#小越越  : 
 可以把光标移动到行首但不换行
View Code
l='a'
print(l)                 #a
print(l,end='%%')     #  a%%    end是print中默认的以换行结尾,这里可以改为%%结尾
print(l,end='%%')    #a%%a%%
print(l,2,3,5,6,sep='%%')     #a%%2%%3%%5%%6      sep是print中元素之间默认用空格隔开,这里可以改成%%
print(l,2,3,5,6)    #a 2 3 5 6
f=open('上课',mode='w',encoding='utf-8')     #打开文件夹,之后通过句柄操作文件
l='mmmm'
print(l,file=f)     #print中file默认在控制台打印,可以把file=f文件句柄,改成在文件中打印
f.close()

f = open('tmp_file','w')
print(123,456,sep=',',file = f,flush=True)
View Code

 (4)内存相关 2

  id(o) o是参数,返回一个变量的内存地址

  hash(o) o是参数,返回一个可hash变量的哈希值,不可hash的变量被hash之后会报错。

  hash函数会根据一个内部的算法对当前可hash变量进行处理,返回一个int数字。

  *每一次执行程序,内容相同的变量hash值在这一次执行过程中不会发生改变。

 (5)数据类型相关 1

  type(o) 返回变量o的数据类型

 (6)模块操作相关 1

          __import__导入一个模块

# import time
# print(time.time())   #1515230362.92395
# 等同于以下例子
# t=__import__('time')
# print(t.time())   #1515230362.92395
View Code

(7)帮助方法

  在控制台执行help()进入帮助模式。可以随意输入变量或者变量的类型。输入q退出

  或者直接执行help(o),o是参数,查看和变量o有关的操作。。。

(8)文件操作相关

  open()  打开一个文件,返回一个文件操作符(文件句柄)

  操作文件的模式有r,w,a,r+,w+,a+ 共6种,每一种方式都可以用二进制的形式操作(rb,wb,ab,rb+,wb+,ab+)

  可以用encoding指定编码.

(9)字符串类型代码的执行

# exec和eval都可以执行 字符串类型的代码
# eval有返回值 —— 有结果的简单计算
# exec没有返回值 —— 简单流程控制
# eval只能用在你明确知道你要执行的代码是什么

eval() 将字符串类型的代码执行并返回结果

eval 把有意义的字符串执行  ,有返回值
# print(eval('1+2'))       #3
eval('1+2')         #什么也没有显示
# eval("print('美丽')")   #美丽
# print(eval("print('美丽')"))   #美丽  None
# print(print('美丽'))    #None

exec()将自字符串类型的代码执行

print(exec("1+2+3+4"))
exec("print('hello,world')")
 exec 把有意义的字符串执行,简单的流程控制,没有返回值
# exec('for i in range(5):print(i)') #0,1,2,3,4 不能用eval
# exec('print(1+2)') #3
# exec('1+2') # 什么也没有显示
# print(exec('1+2')) #None
# print(exec('print(1+2)'))

compile  将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值

参数说明:   

1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。  

2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。  

3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'。

 

复制代码
>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
1
3
5
7
9


>>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)


>>> #交互语句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single')
>>> name #执行前name变量不存在
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    name
NameError: name 'name' is not defined
>>> exec(compile3) #执行时显示交互命令,提示输入
please input your name:'pythoner'
>>> name #执行后name变量有值
"'pythoner'"
复制代码
View Code
compile字符串执行 :编译
# ret='for i in range(5):print(i)'
# c=compile(ret,'','exec')    #用exec执行,有返回值
# exec(c)
#
# ret='1+2+3+4'
# c=compile(ret,'','eval')        #''引号原本的功能是放
# print(eval(c))   # 用eval执行,没有返回值,所以需要打印
View Code  

四,基础数据类型相关(38)

  1 和数字相关(14)

  

  数字——数据类型相关:bool,int,float,complex

bool
int    整形
float   # 浮点数(有限循环小数,无限循环小数)  != 小数 :有限循环小数,无限循环小数,无限不循环小数
complex 复数,不能比较大小  实部+虚部   两个部分都是浮点数
1+2j
4+5j
View Code

  数字——进制转换相关:bin,oct,hex

bin   二进制
print(bin(2))   #0b10
oct   八进制
print(oct(2))   #0o2
hex   十六进制
print(hex(2))   #0x2
View Code

  数字——数学运算:abs,divmod,min,max,sum,round,pow

abs  取绝对值
print(abs(-1))
divmod  除余
print(divmod(9,6))    #(1, 3)  商1  余3
round  小数精确
print(round(2.12133112,2))     #2.12
print(round(2,56))    #2
sum   求和   q求和对象是可迭代的  sum(iterable,start)   start开始加的值
错误写法  print(sum(1,2))
print(sum([1,2,3,4]))    #10
print(sum([1,2,3,4],10))     #   第一个数从10 开始加
min   求最小值
print(min(2,5,6,8))   #2
print(min(2,5,6,8,-0.5,key=abs))   #-0.5
max
print(max(2,5,6,8,-1,-8,key=abs))   #8
pow  求幂运算pow(x,y,z)
print(pow(2,3))   # 2的3次方
print(pow(2,3,3)) #幂运算之后再取余2
View Code
2 和数据结构相关 

序列——列表和元组相关的:list和tuple

序列——字符串相关的:str,format,bytes,bytearry,memoryview,ord,chr,ascii,repr

print('今天很{},我很{},是个{}'.format('美好','美丽','美女'))
print(format('美丽','>20'))    #把字符串以20个长度为标准,左靠齐
print(format('美丽','<20'))     #把字符串以20个长度为标准,右靠齐
print(format('美丽','^20'))    #把字符串以20个长度为标准,居中
format
# 需求把gbk编码的转换为utf-8,python是unicode编码,需要先把'你好'转为gbk 形式
print(bytes('美丽',encoding='GBK')) #等价于==print('美丽'.encode('gbk')) #  #b'xc4xe3xbaxc3'把unicode转换为gbk的bytes类型
print((bytes('美丽',encoding='gbk')).decode('gbk').encode('utf-8'))    #转换成功
# 网页编程是二进制存储
# 照片视频也是二进制
# html网页爬取也是二进制
bytes
bytearray(s,encoding='utf-8')  转换编码,特点是可以根据字节码改内容,但是你要提前 知道要改内容的号码
# b_bytes=bytearray('你好',encoding='utf-8')
# print(b_bytes)    #'xe4xbdxa0xe5xa5xbd')
# print(b_bytes[0])   #228
# print(b_bytes[1])   #189
bytearray
视觉展示,只是给我们看,不占用内存,但是要调用是时候还是会占用内存,用处比较少
# memoryview(bytes('hello,eva',encoding='utf-8')
memoryview
ord字符按照unicode转数字
# print(ord('你'))    #20320
# print(ord('1'))    #49
# print(ord('A'))    #65
# print(ord('❤'))    #10084
ord
#数字按照unicode转字符,  但是从65(A)开始才能转换
# print(chr(97))    #a
# print(chr(98))    #
# print(chr(65))    #A
chr
字符在ascii码中的内容就打印出来,不是就转换成u
# print(ascii('你')     #'u4f60'
# print(ascii('A') )    #'A'
ascii
#repr 用于%r格式化输出    ,不同于print的是会将打印内容的数据类型也一起打印出来
# name='egg'
# print('你好%s'%name)   #你好egg
# print('你好%r'%name)   #你好'egg'
# print(repr('1'))     #'1'
# print('1')       #1
# print(repr(1))   #1
repr

序列:reversed,slice

reverse  反转
l=[1,3,6,4]
l.reverse()    #反转l
print(l)
reversed    保留原列表,得到一个反向迭代器
l2=reversed(l)  #生成器
print(l2)    #<list_reverseiterator object at 0x018539D0>
for i in l2:
    print(i)    #4,6,3,1
reversed
t = (1,2,23,213,5612,342,43)
t1=slice(0,5,2)  #slice(0, 5, 2)    切片
print(t1)    #slice(0, 5, 2)
print(t[t1])  # (1, 23, 5612)     把l从索引0到5开始切片按照每隔2个值切片
print(t[slice(0,5,2)])   # (1, 23, 5612)
slice

数据集合——字典和集合:dict,set,frozenset

数据集合:len,sorted,enumerate,all,any,zip,filter,map

enumerate枚举
dic={'a':'b','c':'d'}
for k,i in enumerate(dic,1):
    print(k,i)
# 1 a
    2 c
enumerate
#all  判断是否有bool值是Flase的值,---一假均假---用中括号写进要判断的值,
# print(all([' ','ni','你']))    #True
# print(all(['','ni','你']))    #Flase
#     特殊情况 : print(all([]))    #Ture
# print(all(['']))  #Flase
all
#any 判断bool值是否有True的值-----一真均真
# print(any([' ','ni','你']))    #True
# print(any(['','ni','你']))    #True
# print(any(['']))    #Flase
# print(any([]))    #Flase
any
zip  返回一个迭代器,拉链功能
# a=['a','b']    #列表
# b=['c','d']
# ret=zip(a,b)
# for i in ret:    #('a', 'c')('b', 'd')
#     print(i)
# a={'a','b'}   #字典
# b={'c','d'}
# ret=zip(a,b)
# for i in ret:
#     print(i)     ##('a', 'c')('b', 'd')和上面效果一样
#
# a=['a','b']
# b=['c','d']
# c=['e','f']
# for i in zip(a,b,c):      #('a', 'c', 'e')('b', 'd', 'f')
#     print(i)
##字典、列表、元祖混用拉链
# a=['a','b','g']    #不是一一对应的话,自动去除多余的
# b={'c','d']}  #dict   list   tuple 都可以用zip 来拉链
# c=('e','f'])
# for i in zip(a,b,c):      #('a', 'c', 'e')('b', 'd', 'f')
#     print(i)
zip 返回一个迭代器,拉链功能
#filter  filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,
# filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。
def f(x):
    return x%2==0
g=filter(f,[1,3,5,6,7,8])    #filter 得到是一个迭代器
for i in g:
    print(i)
# filter过滤的功能
# def a(z):
#     return z%2==1     #函数返回值为ture,则放到新的迭代器中
# ret=filter(a,[1,2,3,4,5,6])   #函数名不加括号,因为前面filter要来调用函数名,得到的ret是一个迭代器
# for i in ret:      #不调用不打印
#     print(i)
# 功能解析:把可迭代的值传给某个函数,函数来执行
# def a(z):
#     return z%2==0
# ret=filter(a,[1,2,3,4,5,6])
# for i in ret:
#     print(i)
# 上面那个filter方法等于这个列表推导式的功能
# c=[i for i in [1,2,3,4,5,6] if i%2==1]
# for i in c:
#     print(i)
filter 得到是一个迭代器
# map
# Python中的map函数应用于每一个可迭代的项,返回的是一个结果list。如果有其他的可迭代参数传进来,
# map函数则会把每一个参数都以相应的处理函数进行迭代处理。map()函数接收两个参数,一个是函数,一个是序列,
# map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。

#例题
# L = [1, 2, 3, 4, 5, 6, 7, 8]
# def l(a):
#     return a**2
# g=map(l,L)   #map后得到的也是迭代器
# print(list(g))    #[1, 4, 9, 16, 25, 36, 49, 64]
# for i in g:
#     print(i)
# 结论:filter()之后元素个数会发生改变,map()之后元素个数不会改变
#        #filter只管筛选,不会改变原来的值   map值会改变
map后得到的也是迭代器
sorted   排序,有key,默认Flse  从小到大排序   reverse=True  从大到小排序
# iterable:是可迭代类型;
# key:传入一个函数名,函数的参数是可迭代类型中的每一项,根据函数的返回值大小排序;
# reverse:排序规则.reverse = True降序或者reverse = False升序,有默认值。
# 返回值:有序列表:
#
# l=[2,1,5,7,-10]
# print(sorted(l,key=abs,reverse=True))     #[-10, 7, 5, 2, 1]
# 等同于sort
# l=[2,1,5,7,-10]
# l.sort(key=abs,reverse=True)
# print(l)  #[-10, 7, 5, 2, 1]
#
# sort使用方法
# l=[2,1,5,7,-10]
# l.sort()
# print(l)   #[-10, 1, 2, 5, 7]
sorted
sorted 与sort的区别
sorted是一个函数,sort是一个方法
sorted 可以传三个参数,sort只能传一个
sorted 可以对迭代器排序,sort 不可以
sorted 直接生成新list,sort更改原list
sorted最强大的地方就是,参数中可带函数。
会根据函数内操作对排序内容进行特定的排序。
sorted 与sort的区别

五,

# 某个方法属于某个数据类型的变量,就用.调用
# 如果某个方法不依赖于任何数据类型,就直接调用 —— 内置函数 和 自定义函数

六,匿名函数

匿名函数:为了解决那些功能很简单的需求而设计的一句话函数

#这段代码
def calc(n):
    return n**n
print(calc(10))
 
#换成匿名函数
calc = lambda n:n**n
print(calc(10))
View Code

现有两元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]
# t1=(('a'),('b'))
# t2=(('c'),('d'))
# ret=zip((('a'),('b')),(('c'),('d')))
# for i in ret:
#     print(i)
# aaa=map(lambda a:{a[0]:a[1]},ret)
# for i in aaa:
#     print(i)

以下代码的输出是什么?请给出答案并解释。
def multipliers():
    return [lambda x:i*x for i in range(4)]
print([m(2) for m in multipliers()])
请修改multipliers的定义来产生期望的结果。
面试题练一练

匿名函数一般与 map,fliter,max,min,sorted 混用。

 

 
原文地址:https://www.cnblogs.com/olivia2018/p/8195746.html