匿名函数与内置函数
匿名函数与常用内置函数
一.匿名函数
没有名字的函数 需要使用关键字lambda
语法结构:
lambda 形参:返回值
使用场景:
lambda a, b:a + b
匿名函数一般不单独使用 需要配合其他函数一起用
二内置函数
1.常用内置函数
1.map() 映射
l1 = [1, 2, 3, 4, 5]
# def func(a):
# return a + 1
# 当我们使用定义函数的方式实现列表中每个数据加1的需求时
res = map(lambda x:x+1, l1) # map关键字的使用
print(list(res)) # 相当于将l1中的每个数据取出来,经过匿名函数处理后,映射出处理后的数据
2.max()\min()
l1 = [11, 22, 33, 44]
res = max(l1)
# max()的作用是找出列表数据中的最大值,min()的作用是找出列表数据中的最小值
d1 = {
'zj': 100,
'jason': 8888,
'berk': 9999999,
'oscar': 1
}
def func(a):
return d1.get(a)
res = max(d1, key=lambda k:d1.get(k))
res = max(d1, key=func)
print(res)
"""当max()或者min()对字典使用时,如果只是用关键字与字典名的话,那么只会根据字典的K键进行取值比对,而在字符编码中A-Z对应65-90,a-z对应97-122,所以如果直接使用max(d1),得到的结果是zj,因为在这个过程中只有字典的键参与,而z对应可了最大值,而在语法结构中,max()括号中除了变量名之外,还可以指定一个key"""
max(d1, key=func),这段代码中,key的作用就是调用函数取出每个键所对应的值作为max取最大值的依据,但是最后得到的结果仍然是键,而不是数据值
3.reduce
from functools import reduce
l1 = [11, 22, 33, 44, 55, 66, 77, 88]
res = reduce(lambda a, b: a + b, l1)
# reduce(匿名函数, 列表名)
print(res)
# reduce的使用需要调用模块,它的作用是去除列表中的每个数据值,经过临时函数处理后,得到所有数据值的总和
三.重要内置函数
1.zip
压缩几组数据值,可以接收多个可迭代的对象,然后把每个可迭代对象中的对应的的元素打包成一个个元组,当对象为多个的时候,会根据数据值最少的那个参数输出的个数,多余部分不输出。
l1 = [11, 22, 33, 44, 55]
l2 = ['jason', 'kevin', 'oscar', 'jerry', 'tony']
l3 = [1, 2, 3, 4, 5]
res = zip(l1, l2, l3)
print(list(res))
# [(11, 'jason', 1), (22, 'kevin', 2), (33, 'oscar', 3), (44, 'jerry', 4), (55, 'tony', 5)]
l1 = [11, 22, 33]
l2 = ['jason', 'kevin', 'oscar', 'jerry', 'tony']
l3 = [1, 2, 3, 4]
res = zip(l1, l2, l3)
print(list(res))
# [(11, 'jason', 1), (22, 'kevin', 2), (33, 'oscar', 3)]
"""补充:
和 Python 3.x 版本不同,Python 2.x 版本中的 zip() 函数会直接返回列表,而不是返回 zip 对象。但是,返回的列表或者 zip 对象,其包含的元素(都是元组)是相同的。"""
2.filter
filter函数(过滤器),筛选方式是采用传入的函数, 去循环数据组中每一个数据,然后将结果为Ture的添加到结果列表中,filter()返回的结果是一个新的列表
l1 = [11, 22, 33, 44, 55, 66, 77, 88]
res = filter(lambda x: x > 40, 11)
print(list(res))
# [44, 55, 66, 77, 88]
3.sorted
与sort()的使用方法类似,默认是升序
l1 = [21, 12, 53, 64, 76, 32, 11, 22]
res = sorted(l1)
print(res)
# [11, 12, 21, 22, 32, 53, 64, 76]
四.常见内置函数了解
1.abs() 绝对值
print(abs(-100)) # 100
print(abs(100)) # 100
2.all()
对条件进行判断,如果给定的条件里面都对就返回Ture,否则就返回False
print(all([0, 1, 2, 3]))
print(all([1, 2, 3, True]))
3.any()
所有数据值对应的布尔值,有一个为True结果就是True 否则返回False
print(any([0, None, '', 1])) # Ture
print(any([0, None, ''])) # False
4.bin()、oct()、hex()、int()
这些是进制转换到函数:二进制,八进制,十六进制,十进制
5.bytes()
转换成bytes类型
s1 = '今天周五,明天周六'
print(s1.encode('utf8'))
print(bytes(s1, 'utf8'))
6.callable()
判断名字是否可以加括号调用
name = 'jason'
def index():
print('from index')
print(callable(name)) # Fallse
print(callable(index)) #Ture
7.chr() ord()
基于ASSCII码表做数字与字母的转换·
print(chr(65)) # A
print(ord('A')) #65
8.dir()
返回括号内对象能够调用的名字
print(dir('hello'))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
9.divmod()
对数据值进行整除,并且可以获得余数
res = divmod(100, 2)
print(res) # (50, 0)
res = divmod(100, 3)
print(res) # (33, 1) 前面的结果是整除的结果,后面是余数
10.enumerate()
枚举 用于将一个可遍历的数据对象(如列表、元组、字符串)组合为一个索引序列,同时列出数据和数据下标,一般结合for循环使用(可人为指定下表开始的数据值):
print(list(enumerate(["a", "b", "c"])))
[(0, 'a'), (1, 'b'), (2, 'c')]
11.eval() exec()
能够识别字符串中的python代码并执行
eval只能执行一些简单的python代码,具有逻辑性的都不行
exec可以识别具有一定逻辑性的python代码
s1 = 'print("哈哈哈")'
eval(s1)
exec(s1)
s2 = 'for i in range(100):print(i)'
eval(s2) # 只能识别简单的python代码 具有逻辑性的都不行,这里会报错
exec(s2) # 可以识别具有一定逻辑性的python代码
12.hash()
加密 使用哈希算法对数据值加密
print(hash('jason'))
# 6504587676088172780
13.id() input() isinstance()
id 返回对象的唯一标识符,标识符是一个整数(返回对象的内存地址)
input 用于接收外界输入的信息
isinstance
判断一个对象是否是一个已知的类型,类似type()
class A:
pass
class B(A):
pass
isinstance(A(), A) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False
14.map() max() min()
map 映射
max 返回最大值
min 返回最小值
15.open()
用于打开一个文件
16.pow()
幂指数(次方)
print(pow(2, 2)) # 4
print(pow(2, 3)) # 8
print(pow(2, 4)) # 16
17.range()
之前讲for循环的时候介绍过,作用是生成一个工厂,生成数据,python2和python3中的作用有所区别python2中的xrange和python3的range作用一样。
18、round
对数值进行四舍五入,但是不太准确,可能是五舍六入。
19、sum
sum(list) : 求取list元素的和