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)])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
生成器
把列表推导式的[]换成()就是生成器表达式
优点:省内存,一次只产生一个值在内存中
t = (i for i in range(10))
print(t)
print(f"next(t): {next(t)}")
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
应用(一般和内置函数联用)
匿名函数通常与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']
正常函数
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']