内置函数和匿名函数

一、匿名函数

什么是匿名函数:就是没有名字的函数
应用场景:临时用一次,通常用于与其他函数配合使用

f=lambda x,y:x+y  #没有名字,可用变量存取调用
print(f)
res=f(1,2)
print(res)
这样子赋值调用太麻烦了,我们通常这样用:
# 调用方式一:
res=(lambda x,y:x+y)(1,2)
print(res)
=====>
3
==================
# 调用方式二:与其他函数配合使用
salaries = {
    'egon': 3000,
    'alex': 100000000,
    'wupeiqi': 10000,
    'yuanhao': 2000
}


def get_salary(name):
    return salaries[name]


print(max(salaries, key=get_salary))  # 名字字符串最大
print(max(salaries, key=lambda name: salaries[name]))  # 工资最大的人
print(min(salaries, key=lambda name: salaries[name]))  # 工资最小的人
print(sorted(salaries))  # 按名字排序
print(sorted(salaries, key=lambda name: salaries[name]))  # 按工资小的排序
print(sorted(salaries, key=lambda name: salaries[name], reverse=True))  # 按工资大的排序
===>
alex
alex
yuanhao
['alex', 'egon', 'wupeiqi', 'yuanhao']
['yuanhao', 'egon', 'wupeiqi', 'alex']
['alex', 'wupeiqi', 'egon', 'yuanhao']

二、内置函数

1、工厂函数

# int整形
# float浮点型
# str字符串
# list列表
# tuple元祖
# dict字典
# set集合
# bool布尔值
# bytes字节数


数据类型转换
with open('user1.txt',mode='wt',encoding='utf-8') as f:
    dic={"egon":"123","tom":"456","jack":"666"}
    f.write(str(dic))

with open('user1.txt',mode='rt',encoding='utf-8') as f:
    data=f.read()
    print(data,type(data))
    dic=eval(data)
    print(dic["egon"])
    print(dic, type(dic))
==============>>
{'egon': '123', 'tom': '456', 'jack': '666'} <class 'str'>
123
{'egon': '123', 'tom': '456', 'jack': '666'} <class 'dict'>

2、常用功能

print(abs(-11))
print(abs(0))
print(abs(11))
===》
11
0
11

print(all(''))
print(all([]))
print(all([11,222,333,0]))
===》
True
True
False

print(any(''))
print(any([]))
print(any([0,None,'',1]))
print(any([0,None,'']))
===》
False
False
True
False

print(bin(11))
print(oct(11))
print(hex(11))
===》
0b1011
0o13
0xb

print(callable(len))
===》
True

l=eval("[1,2,3]")
print(l)
====>
[1,2,3]

3、ASCII表:

65-90 A-Z
print(chr(65))
A
print(ord('A'))
65
print(chr(90))
Z

4、面向对象重点

classmethod(x)
staticmethod(x)
setattr(x,y,z)
getattr(x,y)
delattr(x,y)
hasattr(x,y)
dir(x)
exec(x)
原文地址:https://www.cnblogs.com/qiukangle/p/14115248.html