如何理解Python cook book中的一段代码
迷茫
迷茫 2017-04-17 17:52:37
0
2
341
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 会有这种书写形式?

谢谢

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
小葫芦

head+sum(tail) if tail else head is a whole

For examplea 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template