总结嵌套列表值的函数?

时间:2014-12-03 03:35:36

标签: python list recursion nested sum

所以我试图创建一个递归函数,它将列表中的每个项目完全相加,现在我知道这是一个简单的内置函数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()

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

答案 2 :(得分: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