python学习day15 day16 内置函数、匿名函数
https://www.processon.com/view/link/5bdc4fe3e4b09ed8b0c75e81
进制转换
print(bin(10)) # 二进制 0b1010 print(oct(10)) # 八进制 0o12 print(hex(10)) # 十六进制 0xa
例子:
print(locals()) #返回本地作用域中的所有名字 print(globals()) #返回全局作用域中的所有名字 global 变量 nonlocal 变量
print(hash(12345)) print(hash('hsgda不想你走,nklgkds')) print(hash(('1','aaa'))) # 哈希地址 print(hash([])) # 报错
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print """ print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) file: 默认是输出到屏幕,如果设置为文件句柄,输出到文件 sep: 打印多个值之间的分隔符,默认为空格 end: 每一次打印的结尾,默认为换行符 flush: 立即把内容输出到流文件,不作缓存 """
# 打印进度条 import time for i in range(0,101,2): time.sleep(0.1) char_num = i//2 per_str = '\r%s%% : %s\n' % (i, '*'*char_num) \ if i == 100 else '\r%s%% : %s' % (i, '*'*char_num) # \r是回到行首 print(per_str, end=' ', flush=True)
字符串类型代码的执行
http://www.cnblogs.com/Eva-J/articles/7266087.html
exec和eval都可以执行 字符串类型的代码
eval有返回值 —— 有结果的简单计算
exec没有返回值 —— 简单流程控制
eval只能用在你明确知道你要执行的代码是什么
code = '''for i in range(10): print(i*'*') ''' exec(code) code1 = 'for i in range(0,10): print (i)' compile1 = compile(code1,'','exec') exec(compile1) code2 = '1 + 2 + 3 + 4' compile2 = compile(code2,'','eval') print(eval(compile2)) code3 = 'name = input("please input your name:")' compile3 = compile(code3,'','single') exec(compile3) # please input your name: 执行时显示交互命令,提示输入 print(name) #
sum接收的是可迭代对象
ret = sum([1,2,3,4,5,6]) # 接收的是可迭代的对象 print(ret) ret = sum([1,2,3,4,5,6,10],10) # 初始加10 print(ret)
print(max([1,2,3,4])) # 4 print(max(1,2,3,-4)) print(max(1,2,3,-4,key = abs)) # -4 以绝对值论最大值
匿名函数
def add(x,y): return x+y add = lambda x,y:x+y print(add(1,2))
max,min,filter,map,sorted这五个内置函数都可以带key,key的值可以是函数,可以用匿名函数代替:
# 求列表中值的平方 def func(x): return x**2 ret = map(func,[-1,2,-3,4]) for i in ret: print(i) ret = map(lambda x:x**2,[-1,2,-3,4])
应用:
1,一般寻找字典中最大值是按照key的大小找,现在按照value找最大值所对应的key
# 找出字典中value最大的key dic={'k1':10,'k2':100,'k3':30} def func(key): return dic[key] print(max(dic,key=func)) #根据返回值判断最大值,返回值最大的那个参数是结果 print(max(dic,key=lambda key:dic[key])) # 匿名函数返回dic[key] 按dic[key]排序
2,面试题
现有两元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]
# 方法一 x = (('a'), ('b')) y = (('c'), ('d')) lis = lambda x, y: [{x[0]: y[0]}, {x[1]: y[1]}] print(lis(x, y)) # 方法二,用zip,map ret = zip((('a'),('b')),(('c'),('d'))) res = map(lambda tup:{tup[0]:tup[1]},ret) print(list(res))
3,以下代码的输出是什么?请给出答案并解释。
def multipliers(): return [lambda x: i*x for i in range(4)] print([m(2) for m in multipliers()]) # [6,6,6,6]
其实就是下面:
print([m(2) for m in [lambda x:3*x,lambda x:3*x,lambda x:3*x,lambda x:3*x]]) #[6,6,6,6]
改动:
def multipliers(): return (lambda x: i*x for i in range(4)) # 返回生成器 print([m(2) for m in multipliers()]) # [0,2,4,6]