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

比如[1,2,4,6],最大6,最小1,返回6-1=5
我写的代码:
def checkio(*args):
if not args:
return 0
return 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。

牛魔王的故事
浏览 128回答 1
1回答

catspeake

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         C 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)
打开App,查看更多内容
随时随地看视频慕课网APP