python中重要的内置函数
Posted 铁子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中重要的内置函数相关的知识,希望对你有一定的参考价值。
all判断是否有bool值为False
1 print(all([‘a‘,‘‘,123])) 2 #False
#any判断是否有bool值为True
1 print(any([‘a‘,‘‘,‘‘])) 2 # True
zip,拉链,不止拉两个,可以拉多个
1 l1 = [1,2,3,‘ef‘,‘rf‘,6] 2 l2 = [‘ew‘,‘d‘,4] 3 l3 = [‘fsd‘,23,43,43,23] 4 print(zip(l1,l2,l3)) 5 for i in zip(l1,l2,l3): 6 print(i) 7 # <zip object at 0x05846738> 8 # (1, ‘ew‘, ‘fsd‘) 9 # (2, ‘d‘, 23) 10 # (3, 4, 43)
filter函数
筛选数字
1 def is_odd(x): 2 return x % 2 == 1 3 4 ret = filter(is_odd, [1,2,3,4,5,6]) #注意这里仅仅用函数的名字 5 print(ret) 6 for i in ret: 7 print(i) 8 # <filter object at 0x057D5270> 9 # 1 10 # 3 11 # 5
筛选字符串
1 def is_str(x): 2 return type(x) == str 3 4 ret = filter(is_str, [123,‘23dwedc‘,‘rewqrrr1‘,12341]) 5 for i in ret: 6 print(i) 7 # 23dwedc 8 # rewqrrr1
筛选去除空的
1 def is_none(s): 2 return s and str(s).strip() 3 ret = filter(is_none,[31,‘asdf‘,‘sdfsad‘,‘‘,‘ ‘,[],234]) 4 for i in ret: 5 print(i) 6 # 31 7 # asdf 8 # sdfsad 9 # 234
过滤1-100中平方根是整数的数
1 import math 2 def is_int(x): 3 return math.sqrt(x) % 1 == 0 4 5 ret = filter(is_int,range(1,101)) 6 for i in ret: 7 print(i) 8 9 # 1 10 # 4 11 # 9 12 # 16 13 # 25 14 # 36 15 # 49 16 # 64 17 # 81 18 # 100
map函数
1 ret = map(abs,[1,-4,6,-8]) 2 for i in ret: 3 print(i) 4 # 1 5 # 4 6 # 6 7 # 8
sorted:在列表不大和想保留原来的数据顺序的时候用
1 l = [1, -4, 6, 5, -10] 2 l.sort() 3 print(l) 4 # [-10, -4, 1, 5, 6] 5 6 7 l = [1, -4, 6, 5, -10] 8 l.sort(key = abs) 9 print(l) 10 # [1, -4, 5, 6, -10] 11 12 l = [1, -4, 6, 5, -10] 13 print(sorted(l)) #sorted(l,key = abs,reverse=True) 14 print(l) 15 # [-10, -4, 1, 5, 6] 16 # [1, -4, 6, 5, -10] 17 18 #根据列表内的元素长度来排序 19 l = [‘ ‘, [1,2], ‘hello world‘] 20 new_l = sorted(l,key=len) #可以给一些函数 21 print(new_l) 22 # [[1, 2], ‘ ‘, ‘hello world‘]
匿名函数
1 def add(x,y): 2 return x + y 3 4 # 变为匿名函数 5 func = lambda x,y:x+y 6 print(func(44,22)) 7 # 66
筛选字典里面值最大的value对应的key
1 dic = {‘key1‘:2, ‘key2‘:3, ‘key3‘:6} 2 def func(key): 3 return dic[key] 4 5 print(max(dic,key=func)) 6 # key3 7 8 dic = {‘key1‘:2, ‘key2‘:3, ‘key3‘:6} 9 print(max(dic,key=lambda k:dic[k])) 10 # key3
带有key的内置函数:min max filter map sorted 都可已和lambda合用
面试题1:用lambda将((‘a‘), (‘b‘))((‘c‘), (‘d‘))转变成[{‘a‘:‘c‘},{‘b‘:‘d‘}]
1 ret = zip(((‘a‘), (‘b‘)),((‘c‘), (‘d‘))) 2 print(list(map(lambda tup:{tup[0]:tup[1]},ret))) 3 4 # [{‘a‘: ‘c‘}, {‘b‘: ‘d‘}]
面试题2:给出答案并解释
1 def multipliers(): 2 return [lambda x:i*x for i in range(4)] 3 print([m(2) for m in multipliers()]) 4 5 # [6, 6, 6, 6]
以上是关于python中重要的内置函数的主要内容,如果未能解决你的问题,请参考以下文章