python高级用法_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)])

[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}")

('name', 'nick')

('age', 19)

('gender', 'male')

zip(keys,values):

info_dict: {}

匿名函数

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

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

print(res)

print(lambda x, y: x+y)

3

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

匿名函数通常与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']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值