2014-12-03 89 views
1

所以即時通訊嘗試創建一個遞歸函數,它需要列表中的每個項目並將其總結,現在我知道了一個簡單的內置函數sum(a),但我試圖使用這樣的嵌套列表下面,但我不斷收到錯誤。彙總嵌套列表值的函數?

def sumList(): 
    list2 = [1, [2, 3,[4, 5, 6], 7, [8, [9, 10]], 11]] 
    newlist = [] 
    lol = 0 
    for i in range (len(list2)): 

     if type(list2[i]) == type([]): 
      print list2[i], "here" 
      for i in range (len(list2[i])): 
       lol += (len(list2[i])) 



      newlist.append(i[:len(i)+1]) 


     if len(list2)==0: 
      return None 
     else: 
      print list2[i] 
      lol+=list2[i] 


    print lol 

sumList() 

現在我知道我在我想象不需要程序實現了很多,但我 不斷收到錯誤

1 
[2, 3, [4, 5, 6], 7, [8, [9, 10]], 11] here 


TypeError: object of type 'int' has no len() 

回答

1

在一般情況下,你可以扁平化您的列表列表並在拼合列表中搜索min。有很多扁平食譜。以下是我從here獲得的一個。

import collections 

def flatten(iterable): 
    for el in iterable: 
     if isinstance(el, collections.Iterable) and not isinstance(el, str): 
      yield from flatten(el) 
     else: 
      yield el 

list2 = [2, 3, [4, 5, 6], 7, [8, [9, 10]], 11] 

print(list(flatten(list2))) 
# [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 
print(sum(flatten(list2))) 
# 65 
0
# Python 2.7 
def recursiveSum(data): 
    # This naively assumes that if it's not an int, it's a list 
    # You may want to add more error handling if you expect dirtier data 
    if isinstance(data, int): return data 
    mySum = 0 
    for i in data: mySum += recursiveSum(i) 
    return mySum 

list2 = [1, [2, 3,[4, 5, 6], 7, [8, [9, 10]], 11]] 
print recursiveSum(list2) # Should get 66 
+0

我只有1 – MrPorba 2014-12-03 03:56:07

+0

我不能重複你的結果的輸出 - 仍出現66我。哪個版本的Python? – rchang 2014-12-03 03:57:46

1
def r_sum(mylist,nsum=0): 
    for i in mylist: 
     if isinstance(i,int): 
      nsum += i 
     else: 
      nsum += r_sum(i) 
    return nsum