python内置函数与匿名函数 一.匿名函数  二. 内置函数与匿名函数的使用

  匿名即没有名字。

#普通函数
def func(x,y,z=1):
    return x+y+z

#匿名函数及没有名字,只有参数列表与return的值表达式,用:分隔
lambda x,y,z=1:x+y+z #与函数有相同的作用域,但是匿名意味着引用计数为0,使用一次就释放,除非让其有名字
func=lambda x,y,z=1:x+y+z 
func(1,2,3)
#让其有名字就没有意义

   匿名函数与有名函数的对比

#有名函数与匿名函数的对比
有名函数:循环使用,保存了名字,通过名字就可以重复引用函数功能

匿名函数:一次性使用,随时随时定义

应用:max,min,sorted,map,reduce,filter

 二. 内置函数与匿名函数的使用

  python中有很多的内置函数,比如常用的max、range、type、getattr、setattr、open等。更多内置函数:https://docs.python.org/3/library/functions.html?highlight=built#ascii

2.1 max、min

  max与min的用法一样,用于获取一个可迭代对象中的最大值与最小值,可以key指定匿名函数自定义返回值用于max、min比较的依据。

# max,min使用方法一致
iterable = [1, 5, 3, 2, 7]
res = max(iterable, key=lambda x: x)  # 参数:可迭代对象遍历的元素;返回值:做比较的值
print(res)  # 7

# 薪资最高
iterable = {
    'Bob': 12000,
    'Tom': 37000,
    'Jerry': 76000,
    'Zero': 120,
}
res = max(iterable, key=lambda x: iterable[x])  # x: 字典的k  返回值:做比较的值
print(res)  # Jerry

2.2 sorted

res = sorted([1, 3, 4, 2, 5], key=lambda x: x, reverse=True)
print(res)  # [5, 4, 3, 2, 1]

iterable = {
    'Bob': [100, 12000],
    'Tom': [200, 37000],
    'Jerry': [50, 76000],
    'Zero': [150, 120],
}
res = sorted(iterable, key=lambda x: iterable[x][0])  # 按value列表的第一个元素大小排序
print(res)  # ['Jerry', 'Bob', 'Zero', 'Tom']

 2.3 map映射

  map会将lambda函数作用于给予的可迭代对象中的每个元素上,之后返回一个迭代器对象

res = map(lambda x: x + 2, [12, 36, 27, 21, 10])
print(list(res))  # [14, 38, 29, 23, 12]

dic = {
    'a': 1,
    'b': 2,
    'c': 3
}
l = [1, 2, 3]

# 将dic的value与列表l的值相加,两个可迭代对象的值数量可以不相等,不相等时以数量少的为主
res = list(map(lambda x, y: dic[x] + y, dic, l))  
print(res)  # [2, 4, 6]

 2.4 filter过滤

  将可迭代对象中让lambda返回值为真的值过滤出来,返回一个迭代器对象

# 将列表中的偶数过滤出来
res = filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])
print(list(res))  # [2, 4]

 2.5 reduce 合并

  将可迭代对象中的元素通过lambda函数合并为一个值,并返回该值。在python3中,reduce使用需要先导入模块。

from functools import reduce
# reduce: 合并 第三个参数默认是None,如果写了的话也会当做队列(列表、元组、集合)的元素参与运算
res = reduce(lambda f, n: f + n, [1, 2, 3, 4, 5])
print(res)  # 15

res = reduce(lambda f, n: f + n, [1, 2, 3, 4, 5], 77)
print(res)  # 92

2.6 abs、pow、sum、divmod

  运算相关。

# 运算
print(abs(-1))  # 绝对值  1 
print(pow(2, 3, 3))  # 2 ** 3 % 3   2
print(sum([1, 2, 3]))  # 求和  6
print(divmod(100, 30))  # 100与30形成商与余数  (3, 10)

2.7  all、any

print(all([1, 2, 'abc']))  # 元素全真为真  True
print(any([1, "", None]))  # 元素有真则真  True

 2.8 zip

  zip可以用于将两个可迭代对象整合为一个字典,第一个参数为key,第二个参数为value,字典键值对个数以长度短的可迭代对象为主,返回的是一个迭代器对象

l1 = ['a', 'b']
l2 = '12345'
res = zip(l1, l2)
print(res)  # <zip object at 0x0233F8C8>
print(dict(res))  # {'a': '1', 'b': '2'}

 2.9 format 格式化

  格式化中有可以转换进制的模式。

#整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
>>> format(3,'b') #转换成二进制
'11'
>>> format(97,'c') #转换unicode成字符
'a'
>>> format(11,'d') #转换成10进制
'11'
>>> format(11,'o') #转换成8进制
'13'
>>> format(11,'x') #转换成16进制 小写字母表示
'b'
>>> format(11,'X') #转换成16进制 大写字母表示
'B'
>>> format(11,'n') #和d一样
'11'
>>> format(11) #默认和d一样
'11'

  实际上 想要转换进制,还可以使用下列方式:

python内置函数与匿名函数
一.匿名函数
 二. 内置函数与匿名函数的使用

  或者使用内置函数:

python内置函数与匿名函数
一.匿名函数
 二. 内置函数与匿名函数的使用

2.10 eval、exec

  实际上元类type生产类时,创建类的名称空间需要exec的参与,eval用于执行表达式,并返回表达式执行的结果,二exec用来执行语句,不会返回任何值。

# eval可以理解将最外层''去除,形成可执行的对象
s = 'print(123)'
eval(s)
s = '{"a": 1}'
res = eval(s)
print(res['a'])

  exec依据字符串给指定的字典加值,只会将字符串中key=value形式加入字典,而且格式比较苛刻,比如a前面加个空格就会报错了。

s = '''
a=1
b=2
4
'''
dic = {}
exec(s, {}, dic)
print(dic)  # {'a': 1, 'b': 2}

  其他示例:

#1、语法
# eval(str,[,globasl[,locals]])
# exec(str,[,globasl[,locals]])

#eval与exec区别
#示例一:
s='1+2+3'
print(eval(s)) #eval用来执行表达式,并返回表达式执行的结果
print(exec(s)) #exec用来执行语句,不会返回任何值
'''
None
'''

#示例二:
print(eval('1+2+x',{'x':3},{'x':30})) #返回33
print(exec('1+2+x',{'x':3},{'x':30})) #返回None

# print(eval('for i in range(10):print(i)')) #语法错误,eval不能执行表达式
print(exec('for i in range(10):print(i)'))

2.11 compile

# compile(str,filename,kind)
# filename:用于追踪str来自于哪个文件,如果不想追踪就可以不定义
# kind可以是:single代表一条语句,exec代表一组语句,eval代表一个表达式
s ='for i in range(3):print(i, end=" ")'
code = compile(s, '', 'exec')
exec(code)  # 0 1 2 

s = '1+2+3'
code=compile(s, '', 'eval')
eval(code)  # ''