1 def sum(items): 2 head, *tails = items 3 return head + sum(tails) if tails else head 4 # 最后一句有点像三目运算符,如果tails为真,则执行前面的sum(tails),否则执行后面的head 5 6 7 num_list = [1,2,3,4,5,6,7,8,9] 8 print(sum(num_list)) 9 # 45
参考资料:
Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).