一、三元表达式
def max(x,y):
if x>y:
return x
else:
returny
这个比较大小的代码,if判断可以用一行代码搞定。
res=x if x >y else y
#条件算一元
#条件成立返回的值算一元
#条件不成立返回的值算一元
二、列表生成式
案例1
l=[]
for i in range (10):
l.append(i)
print(l)
列表生成式
l=[i for i in range (10)]
print(l)
案例2
l=[]
for i in range (10):
if i > 5:
l.append(i)
print(l)
l = [i for i in range (10) if i > 5]
print (l)
案例3
names = ['lxx','hxx','wxx','lili']
l = []
for name in names:
l.append(name + '_sb')
print(l)
l = [name + '_sb' for name in names]
print (l)
案例4
names = ['egon','lxx_sb','hxx_sb','wxx_sb']
res = [name for name in names if name.endswith('sb')]
print(res)
字典生成式
res= {i:i**2 for i in range (5)}
items = [('k1',111),('k2',222),('k3',333)]
print(dict(items))
print({k:v for k,v in items})
集合生成式
res = {i for i in range (5)}
print(res)
生成器表达式
res = (i for i in range (3))
print(res)
#造老母鸡
print(next(res))
print(next(res))
print(next(res))
with open ('a.txt',mode='rt',encond='utf-8')as f:
res= f.read()
print(len(res))
res = 0
for line in f:
res+= len(line)
print(res)
res = sum((len(line) for line in f))
print(res)
#精简
res = sum(len(line) for line in f)
print(res)
三、函数的递归调用
在调用一个函数的内部又调用自己,所以递归调用的本质就是一个循环的过程
def func():
print('func')
func()
func()
import sys
sys.getrecursionlimit()# 查看多少层
print
sys.setrecursionlimit()#设置多少层
大前提:递归调用一定要在某一层结束
递归的两个阶段
1、回溯:向下一层一层挖井
2、递推:向上一层一层返回
四、二分法
例:
nums = [-3,1,3,7,13,23,37,43,57,63,77,91,103]
find_num = 64
def find(nums,find_num):
print(nums)
if len(nums) == 0:#如果列表的长度为0,则输出没有这个值
print("not exists")
return#结束后续操作
mid_index = len(nums) // 2#中间值=列表的长度//2
if find_num > nums[mid_index]:
# in the right
find(nums[mid_index+1:],find_num)
elif find_num < nums[mid_index]:
# in the left
find(nums[:mid_index], find_num)
else:
print('you got it')
find(nums,find_num)
五、匿名函数
匿名函数:没有名字的函数
特点:临时用一次
def f(x,y):
return x+y
lambda x,y:x+y
#使用:(lambda x,y:x+y)()
salaries = {
"egon":3000,
"tom":1000000,
"zxx":1000
}
print(max([11,22,33]))
print(max(salaries.values()))
print(max(salaries))
def func(k):
return salaries[k]
print(max(salaries,key=func))
print(max(salaries,key=lambda k:salaries[k]))
print(min(salaries,key=lambda k:salaries[k]))
print(sorted(salaries,key=lambda k:salaries[k]))
print(sorted(salaries,key=lambda k:salaries[k],reverse=True))
补充:
map
names = ["lxx",'hxx',"wxx",'lili']
规则
"lxx_sb","hxx_sb"
l = (name + "_sb" for name in names)
res = map(lambda name:name + "_sb",names)
print(list(res))
filter
names = ["lxx_sb",'egon',"wxx_sb",'lili_sb']
print([name for name in names if name.endswith('sb')])
res = filter(lambda name:name.endswith('sb'),names)
print(list(res))
reduce
from functools import reduce
res = reduce(lambda x,y:x+y,[1,2,3])
res = reduce(lambda x,y:x+y,["aa","bb","cc"])
print(res)
res = pow(10,2,3) # 10 ** 2 % 3
print(res)