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 会有这种书写形式?
谢谢
业精于勤,荒于嬉;行成于思,毁于随。
head+sum(tail) if tail else head is a whole
head+sum(tail) if tail else head
For examplea if a > b else b等价于max(a, b)等价于(a>b)?a:b
a if a > b else b
max(a, b)
(a>b)?a:b
This is syntactic sugar for python, because early python programmers like to use various hacks to implement ? expressions, so python provides this form in syntax
This is a ternary expression in Python
head+sum(tail) if tail else head
is a wholeFor example
a if a > b else b
等价于max(a, b)
等价于(a>b)?a:b
This is syntactic sugar for python, because early python programmers like to use various hacks to implement ? expressions, so python provides this form in syntax
This is a ternary expression in Python