为了账号安全,请及时绑定邮箱和手机立即绑定

如下版本A中if else为什么不用分号? 版本B我不明白为什么这么写?

如下版本A中if else为什么不用分号? 版本B我不明白为什么这么写?

牛魔王的故事 2022-05-24 19:15:05
比如[1,2,4,6],最大6,最小1,返回6-1=5我写的代码:def checkio(*args):if not args:return 0return max(args)-min(args)另外两个写得更简洁的代码:版本A:def checkio(*args):return max(args) -min(args) if args else 0版本B:def checkio(*t):return len(t) and max(t)-min(t)版本A中if else为什么不用分号?版本B我不明白为什么这么写能实现和我一样的功能。len(t)是一个数值,max(t)-min(t)是一个数值,两个数值and一下,怎么就能实现这个功能了呢?谢谢!当输入为空的list的时候返回0。
查看完整描述

1 回答

?
catspeake

TA贡献1111条经验 获得超0个赞


A :if ...:       pass   else:       pass    这是正规的python if else 语句 用啥分号?    B 应该这样子写才对吧 def checkio(args):    return max(args) -min(args) if args else 0等价于 def checkio(args):    if args :        return max(args) -min(args)    else:        return  0         def checkio(t):    return len(t) and max(t)-min(t)     等价于 def checkio(t):    if len(t)==0:        return  len(t)    else:        return max(t)-min(t)


查看完整回答
反对 回复 2022-05-30
  • 1 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号