day25

匿名函数

匿名--》没有名字--》没办法调用--》只能和某些办法联用

语法

lambda 参数:返回值

如果真的要用,会变成有名函数

f = lambda x, y:x * y
res = f(1, 2)
print(res)

使用方法

有max/min/filter/map/sorted

max 返回最大值

salary_dict = {
    'nick':3000,
    'jason':100000,
    'tank':5000,
    'sean':2000
}

res = masx(salaey_dict, key=lambda name:salary_dict[name]) # 默认key的首字母
print(res)

# key = func 默认做的事情
# 1.循环遍历salary_dict,会取到所有的key值
# 2.然后把所有的key值一次丢入func中,然后返回薪资
# 3.通过返回的薪资排序,得到最大值

min 返回最小值

res = min(salary_dict,key=lambda name:salary_dict[name])
print(res)

filter 筛选

#def func(item):
#    if item < 5:
#        return  True
#    else:
#        return False
#    
#res = filter(func,[1,2,3,4])
res = filter(lambda item:item>2,[1,2,3,4])
print(res) # 迭代器
print(list(res))

map 映射

def func(item):
    return item + 2

res = map(func,[1,2,3,])
print(res)
print(list(res))

sorted 排序

def function2(item):
    return salary_dict[item]

# res = sorted([2,3,4,1,0,5], key=function2,reverse=True)
res = sorted(salary_dict,key=function2,reverse=True)

python解释器内置方法

重要部分

bytes

res = bytes('中国',encoding='utf8')
print(res)

chr/ord

print(chr(97))
print(ord('a'))

divmod 分栏(取余/取整)

print(divmod(10,4))

enumerate

lt = [1,2,3]
for i in range(len(lt)):
    print(i,lt[i])
    
for ind,val in enumerate(lt):
    print(ind,val)

eval

把字符串的引号去掉,留下来的是什么就是什么

s = '"abc"'
print(type(eval(s)), eval(s))

hash,可变不可哈希

print(hash(123123))

了解

abs 绝对值

print(abs(-1))

all 可迭代对象内的元素全部为True,则为True

print(all(1,2,3,4))

any

print(any([0,0, ]))

bin/oct/hex

二进制/八进制/十六进制

print(bin(123))
print(oct(123))
print(hex(123))

dir 列出模块的所有方法

import time

print(dir(time))

frozenset

不可变化的集合,类似于元组

s = frozenset({1,2,3})
print(s)

globals/locals

print(globals()) # 列出所有全局变量
print('locals():',locals())

pow

阶乘

print(pow(2,2))

round

print(round(10,333))

slice

s = slice(1,5,2) # start,stop,step
lt = [1,2,3,4,5,6,7]
print(lt[s])
print(lt[1:5:2])

sum

print(sum([1,2,3,4,5]))

__import__

通过字符串导入模块

time = __import__('time')
print(time.time())

异常处理

try:
    pass
except Exception as e: # 万能异常,只要有错误,就捕捉
    print(e) # 错误的描述信息
    print('出现错误')

# 异常捕捉只能捕捉逻辑错误
fr = open('test.py')
try:
    # 文件中途报错
    1/0
    fr.close()
except Exception as e:
    print(e)

finally: # 无论你报不报错,都执行这一行
    print('fianlly')
    
# raise 主动抛错误
posted @ 2019-09-25 22:32  Isayama  阅读(105)  评论(0编辑  收藏  举报