items=[1,2,3,4]
def sum(items):
head,*tail = items
return head+sum(tail) if tail else head
上述代码中的if tail else head如何理解?为何if else 会有这种书写形式?
谢谢
items=[1,2,3,4]
def sum(items):
head,*tail = items
return head+sum(tail) if tail else head
上述代码中的if tail else head如何理解?为何if else 会有这种书写形式?
谢谢
4 回答4.5k 阅读✓ 已解决
1 回答3.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
1 回答4.5k 阅读✓ 已解决
1 回答3.9k 阅读✓ 已解决
2 回答428 阅读✓ 已解决
head+sum(tail) if tail else head
是一个整体比如
a if a > b else b
等价于max(a, b)
等价于(a>b)?a:b
这是python的语法糖,因为早期的python程序员喜欢用各种hack来实现?表达式,所以python在语法上提供了这种形式