Python高级用法

Python高级用法

三元表达式

x = 10
y = 20
print(x if x > y else y)
x = 100
y = 20
print(x if x > y else y)

20

100

列表推导式

print([i for i in range(10)])
print([i*2 for i in range(10)])
print([i-1 for i in range(10)])

字典生成器

zip()返回一个zip对象,其内部元素为元组;可以转化为列表或者元组

keys = ['name', 'age', 'gender']
values = ['nick', 19, 'male']
res = zip(keys, values)
print(res)
for i in res:
    print(i)
print(F"zip(keys,values): {zip(keys,values)}")

info_dict = {k: v for k, v in res}
print(f"info_dict: {info_dict}")

<zip object at 0x000001D6D7870E08>
('name', 'nick')
('age', 19)
('gender', 'male')
zip(keys,values): <zip object at 0x000001D6D7870E88>
info_dict: {}

匿名函数

匿名函数就是一个没有变量名的函数对象

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

3
<function at 0x000001958A013E18>

应用(一般和内置函数联用)

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

举例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']

正常函数

扫描二维码关注公众号,回复: 7015087 查看本文章
name_list = ['nick', 'jason sb', 'tank sb', 'sean sb']
def zx(name):
    return name.endswith('sb')

filter_res = filter(zx, name_list)
print(f"list(filter_res): {list(filter_res)}")

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

猜你喜欢

转载自www.cnblogs.com/zx125/p/11348838.html