匿名函数与内置函数

匿名函数

有名函数

定义的函数基于函数名使用

def func():
    print('from func')
func()

from func

匿名函数

没有绑定名字,使用一次即被收回,加括号就可以运行

lambda关键字

语法:lambda x,y:x+y

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

3

与内置函数联用

匿名函数通常与max()、sorted()、map()、filter()方法联用。

max()

取最大值

salary_dict = {
    'nick': 3000,
    'jason': 100000,
    'tank': 5000,
    'sean': 2000
}
print(max(salary_dict))  # 只是从key中比较大小

def func(k):
    return salary_dict[k]
print(max(salary_dict,key=func))  # 会比较key对应的value值,返回最大的key

tank

jason

sorted()

从小到大排序

lis = [1, 3, 2, 5, 8, 6]
sorted(lis)
print(lis)
print(sorted(lis))

[1, 3, 2, 5, 8, 6]

[1, 2, 3, 5, 6, 8]

salary_dict = {
    'nick': 3000,
    'jason': 100000,
    'tank': 5000,
    'sean': 2000
}
print(sorted(salary_dict,key=lambda name:salary_dict[name]))

['sean', 'nick', 'tank', 'jason']

map()

映射

name_list = ['jason', 'tank', 'sean']

res = map(lambda name: f"{name} sb", name_list)
print(f"list(res): {list(res)}")

list(res): ['jason sb', 'tank sb', 'sean sb']

filter()

过滤

name_list = ['nick', 'jason sb', 'tank sb', 'sean sb']

filter_res = filter(lambda name: name.endswith('sb'), name_list)
print(f"list(filter_res): {list(filter_res)}")

list(filter_res): ['jason sb', 'tank sb', 'sean sb']

内置函数

55内置函数-内置函数.jpg

更多内置函数:https://docs.python.org/3/library/functions.html?highlight=built#ascii

bytes()

解码字符

res = '你好'.encode('utf8')
print(res)

b'\xe4\xbd\xa0\xe5\xa5\xbd'

res = bytes('你好', encoding='utf8')
print(res)

b'\xe4\xbd\xa0\xe5\xa5\xbd'

chr()/ord()

chr()参考ASCII码表将数字转换成对应字符;ord()将字符转换成对应的数字

print(chr(65))
print(ord('A'))

A

65

divmod()

分栏

print(divmod(10,3))

(3,1)

enumerate()

带有索引的迭代

l = ['a', 'b', 'c']
for i in enumerate(l):
    print(i)

(0, 'a')
(1, 'b')
(2, 'c')

eval()

把字符串翻译成数据类型

lis = '[1,2,3]'
lis_eval = eval(lis)
print(lis_eval)

[1, 2, 3]

hash()

是否可哈希

print(hash(1))

1

posted @ 2019-06-05 15:07  小小罗code  阅读(137)  评论(0编辑  收藏  举报