python--内置函数、匿名函数、递归调用
匿名函数
有名函数:
def func1(x): return x**2 print(func1) 结果: <function func1 at 0x00000000005C3E18>
匿名函数:
func2=lambda x: x**2 print(func2) 结果: 4
f1=lambda x,y:x+y print(f1(1,2)) 结果: 3
f2=lambda x:x>1 print(f2(3)) 结果: True
salaries={ 'egon':3000, 'alex':100000000, 'wupeiqi':10000, 'yuanhao':2000 } print(max(salaries,key=lambda x:salaries[x])) 结果: alex
内置函数
字典的运算:最小值min,最大值max,排序sorted
迭代字典,取得是key,因而比较的是key的最大和最小值
可以取values,来比较
>>> max(salaries.values())
>>> min(salaries.values())
但通常我们都是想取出,工资最高的那个人名,即比较的是salaries的值,得到的是键
>>> max(salaries,key=lambda k:salary[k])
'alex'
>>> min(salaries,key=lambda k:salary[k])
'yuanhao'
也可以通过zip的方式实现
salaries_and_names=zip(salaries.values(),salaries.keys())
先比较值,值相同则比较键
>>> max(salaries_and_names)
(100000000, 'alex')
salaries_and_names是迭代器,因而只能访问一次
>>> min(salaries_and_names)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence
salaries={ 'egon':3000, 'alex':100000000, 'wupeiqi':10000, 'yuanhao':2000 } print(max(salaries)) #迭代字典,取得是key,因而比较的是key的最大和最小值 print(max(salaries.values())) 结果: yuanhao 100000000
salaries={ 'egon':3000, 'alex':100000000, 'wupeiqi':10000, 'yuanhao':2000 } res=zip(salaries.values(),salaries.keys()) for i in res: print(i) 结果: (3000, 'egon') (100000000, 'alex') (10000, 'wupeiqi') (2000, 'yuanhao')
salaries={ 'egon':3000, 'alex':100000000, 'wupeiqi':10000, 'yuanhao':2000 } res=zip(salaries.values(),salaries.keys()) print(max(res)[-1]) 结果: alex
print(max([1,2,3,4,5])) print( max( i for i in range(10) ) ) 结果: 5 9
# min函数
# map:映射
l=[1,2,3,4] m=map(lambda x:x**2,l) print(list(m)) 结果: [1, 4, 9, 16]
names=['alex','wupeiqi','yuanhao'] print(list(map(lambda item:item+'_SB',names))) 结果: ['alex_SB', 'wupeiqi_SB', 'yuanhao_SB']
#reduce:合并
from functools import reduce res=0 for i in range(100): res+=i print(res) print(reduce(lambda x,y:x+y,range(100),100)) 结果: 4950 5050
# filter:过滤
names=['alex_sb','yuanhao_sb','wupeiqi_sb','egon'] print(list(filter(lambda name:name.endswith('_sb'),names))) 结果: ['alex_sb', 'yuanhao_sb', 'wupeiqi_sb']
#divmod函数 (求商和余数)
print(divmod(73,23)) total_count=73 per_count=23 res=divmod(total_count,per_count) if res[1] > 0: page_count=res[0]+1 print(page_count) 结果: (3, 4) 4
#enumerate函数
l=['a','b','c'] for i in enumerate(l): print(i) dic={'name':'egon','age':18} for i in enumerate(dic): print(i) 结果: (0, 'a') (1, 'b') (2, 'c') (0, 'name') (1, 'age')
s=set({1,2,3}) s.add(4) s.pop() print(s) 结果: {2, 3, 4}
s=frozenset({1,2,3})
print(globals() is locals()) 结果: True
s1='hello123123' s2=' hello123123' print(hash(s1)) print(hash(s2)) 结果: -685577854101050435 -1412206003061893942
print(type(1)) print(isinstance(1,int)) 结果: <class 'int'> True
# iter([1,2,3]) #[1,2,3].__iter__()
print(pow(3,2,2)) #3**2%2 结果: 1
for i in range(-5,0): print(i) 结果: -5 -4 -3 -2 -1
for i in range(0,5,2): #0 2 4 print(i) 结果: 0 2 4
for i in range(5,0,-1): #0 2 4 print(i) 结果: 5 4 3 2 1
l=['a1','a2','a3','a4','a5','a6','a7','a8','a9'] print(l[2:5:2]) print(l[::2]) print(l[::-1]) 结果: ['a3', 'a5'] ['a1', 'a3', 'a5', 'a7', 'a9'] ['a9', 'a8', 'a7', 'a6', 'a5', 'a4', 'a3', 'a2', 'a1']
l1=[3,5,1,2] print(list(reversed(l1))) print(l1) l1=list(reversed(l1)) 结果: [2, 1, 5, 3] [3, 5, 1, 2]
print(round(3.3456,3)) 结果: 3.346
l=['a1','a2','a3','a4','a5','a6','a7','a8','a9'] print(l[2:5:2]) x=slice(2,5,2) print(l[x]) l1=[1,2,3,4,5] print(l1[x]) 结果: ['a3', 'a5'] ['a3', 'a5'] [3, 5]
print(sum(i for i in range(101))) print(sum([1,2,3,4])) 结果: 5050 10
#sorted
sorted(iterable,key=None,reverse=False)
l=[1,2,4,9,-1] print(sorted(l)) #从小到大 print(sorted(l,reverse=True)) #从大到小 结果: [-1, 1, 2, 4, 9] [9, 4, 2, 1, -1]
# vars()
name='alex' res='SB' if name == 'alex' else 'shuai' print(res) egg_list=['鸡蛋%s' %i for i in range(10)] #列表解析 print(egg_list) egg_g=('鸡蛋%s' %i for i in range(10)) #生成器表达式 print(egg_g) s='hello' print([True for i in s if i == 'e']) 结果: shuai ['鸡蛋0', '鸡蛋1', '鸡蛋2', '鸡蛋3', '鸡蛋4', '鸡蛋5', '鸡蛋6', '鸡蛋7', '鸡蛋8', '鸡蛋9'] <generator object <genexpr> at 0x0000000002194990> [True]
递归
'''
递归调用:
在调用一个函数的过程中,直接或者间接调用了该函数本身
'''
直接调用:
def func(): print('====>func') func() func()
间接调用:
def foo(): print('from foo') bar() def bar(): print('from bar') foo() foo()
来个栗子:
def age(n): if n == 5: return 18 return age(n+1)+2 print(age(1)) 结果: 26
一个列表嵌套很多层,用递归取出所有的值
l=[1,[2,3,[4,5,[6,7,[8,9,[10,11,[12,13]]]]]]] def func(l): for i in l: if isinstance(i,list): func(i) else: print(i) func(l) 结果: 1 2 3 4 5 6 7 8 9 10 11 12 13
补充内容
求商品总价:
文件内容:
apple 10 3 tesla 100000 1 mac 3000 2 lenovo 30000 3 chicken 10 3
low版:
moneys=[] with open('goods',encoding='utf-8') as f: for line in f: l=line.split() price=float(l[1]) count=int(l[2]) moneys.append(price * count) # print(moneys) print(sum(moneys)) 结果: 196060.0
列表解析:
with open('goods',encoding='utf-8') as f: l=[float(line.split()[1]) * int(line.split()[2]) for line in f] print(sum(l)) 结果: 196060.0
生成器表达式:
with open('goods',encoding='utf-8') as f: print(sum(float(line.split()[1]) * int(line.split()[2]) for line in f)) 结果: 196060.0
模拟数据库查询
low版:
goods_info=[] with open('goods',encoding='utf-8') as f: for line in f: l=line.split() name=l[0] price=l[1] count=l[2] goods_info.append({'name':name,'price':price,'count':count}) print(goods_info) 结果: [{'name': 'apple', 'price': '10', 'count': '3'}, {'name': 'tesla', 'price': '100000', 'count': '1'}, {'name': 'mac', 'price': '3000', 'count': '2'}, {'name': 'lenovo', 'price': '30000', 'count': '3'}, {'name': 'chicken', 'price': '10', 'count': '3'}]
列出价格大于3000的商品信息:
with open('goods',encoding='utf-8') as f: goods_info=[{'name':line.split()[0],'price':float(line.split()[1]),'count':int(line.split()[2])} for line in f \ if float(line.split()[1]) > 3000] print(goods_info) 结果: [{'name': 'tesla', 'price': 100000.0, 'count': 1}, {'name': 'lenovo', 'price': 30000.0, 'count': 3}]