map/filter/sorted/enumerate/zip…
这20个函数
帮你少写90%的for循环
1、map函数,逐一对序列进行函数计算。
>>> list(map(lambda x: x*2, [1,2,3]))[2, 4, 6]
2、filter函数,对序列进行函数级的条件过滤。
>>> list(filter(lambda x: x>2, [1,2,3]))[3]
3、sorted函数,对序列进行排序操作。
>>> sorted([3,1,2], reverse=True)[3, 2, 1]
4、enumerate函数,按序对目标序列元素进行逐一操作。
>>> for i,v in enumerate(['a','b']):... print(i,v)... 0 a1 b
5、zip函数,对多个序列对象进行按序打包重组。
>>> list(zip([1,2],[3,4]))[(1, 3), (2, 4)]>>> list(zip([1,2],[3,4,5]))[(1, 3), (2, 4)]>>> list(zip([1,2],[3,4,5],[6,7]))[(1, 3, 6), (2, 4, 7)]
6、any/all函数,全元素逻辑判断
# any -> 任意元素为真则为真 >>> any([0,0,0])False>>> any([0,0,2])True# all -> 全部元素为真则为真 >>> all([0,1,2])False>>> all([1,1,2])True
7、sum/max/min/divmod函数,计算目标对象的和、最大值、最小值,以及商和余数。
# 求和 >>> sum([2,4,7,3,1])17# 求最大值 >>> max([2,4,7,3,1])7# 求最小值 >>> min([2,4,7,3,1])1# 直接求商和余数 >>> divmod(10,3)(3, 1)
8、len函数,计算目标对象的长度。
>>> len([1,2,3,4])4>>> len('hello world')11
9、isinstance函数,用于目标类型判断。
>>> isinstance(123, int) True>>> isinstance('123', int)False
10、getattr函数,获取对象的某个属性值。
>>> class animal():... def __init__(self,name=''):... self.name = name... >>> cat = animal('Rose')>>> getattr(cat,'name')'Rose'
11、setdefault方法,更安全访问字典,访问不存在的键则创建为默认值,已存在的键则读取当前值。
>>> d = {'a':1,'b':2,'c':3}>>> d.setdefault('d',0)0>>> d{'a': 1, 'b': 2, 'c': 3, 'd': 0}>>> d.setdefault('d',4)0>>> d{'a': 1, 'b': 2, 'c': 3, 'd': 0}
12、defaultdict函数,自动向字典中添加没有的元素为默认值
>>> from collections import defaultdict>>> d = defaultdict(int)>>> ddefaultdict(<class 'int'>, {})>>> d[2]0>>> ddefaultdict(<class 'int'>, {2: 0})
这里要注意,defaultdict创建的字典虽然和python中的字典用法很像,但实际上是一种新的字典类型。13、Counter函数,自动完成序列内各值的统计数据。
>>> from collections import Counter>>> Counter(['a','b','a','c','a']) Counter({'a': 3, 'b': 1, 'c': 1})
14、chain函数,连接多个同类型对象。
>>> from itertools import chain>>> list(chain([1,2],[3,4])) [1, 2, 3, 4]
注意,上面这里使用了list()函数将chain的结果进行了列表转换。这是因为chain函数返回的是一个可迭代对象,使用时才会创建数据,为了展示必须使用list()函数进行强制类型转换。
15、partial函数,固定函数的部分参数。
>>> from functools import partial# 创建一个指数函数,底数、指数均可设置>>> def power(base,exponent):... return base**exponent... # 将指数固定为2,实现平方计算函数 >>> square = partial(power,exponent=2)>>> square(3)9>>> square(4)16
16、reduce函数,对序列进行累积计算。
>>> from functools import reduce>>> reduce(lambda a,b: a+b, [1,2,3,4])10>>> reduce(lambda a,b: a*b, [1,2,3,4])24
17、next函数,让可迭代对象移动到下一个具体值。
>>> arr_iter = iter([1,2,3,4])>>> next(arr_iter)1>>> next(arr_iter)2>>> next(arr_iter)3
18、callable函数,判断目标对象是否可调用。
>>> callable(lambda x: x) True
19、globals/locals函数,获取所有全局变量、局部变量
>>> globals(){'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}>>> locals(){'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
20、type-hint语法,让变量、函数返回值也有类型身份
# :用于变量类型注解 ,->用于函数返回值类型注解 def f(x: int) -> str: pass
注意,虽然使用了type-hint语法,但其不像其他语言是类型强制的。在Python中,类型注解仅仅展示可读性,并不做类型锁定。
-------------------------它是数字世界里的一把杀猪刀
却总能巧夺天工
它的世界是纯粹0、1组合
却总能创造无尽幻想
......
本公众号关注数据价值分析、编程学习,将不定期更新社会热点数据分析结果、编程技巧,分享数据分析工具、方法、学习等内容,欢迎有兴趣的小伙伴加入。