items = [1,2,3,4,5,6] 結果: 1 [2, 3, 4, 5, 6] 2 [3, 4, 5, 6] 3 [4, 5, 6] 4 [5, 6] 5 [6] 6 []
方法一:python
def sum(items): #遞歸 head,*tail = items print(head,tail) return head + sum(tail) if tail else head
方法二:ide
def sum(items): #解包 tail = items while tail: head,*tail = tail print(head,tail)
方法三:遞歸
def sum(items): #切片 tail = items while tail: print(tail[:1][0],tail[1:]) tail = tail[1:]
方法四:it
items = [1,2,3,4,5,6] def sum(items): #list方法 while items: print(items[0],items[1:]) items.pop(0)