繁体   English   中英

汇总嵌套列表值的函数?

[英]function that sums up nested list values?

因此,我试图创建一个递归函数,将列表中的每个项目都取下来,然后将其汇总起来,现在我知道有一个简单的内置函数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()

通常,您可以展平列表列表并在展平列表中搜索min。 有许多扁平化的食谱。 下面是我从这里带走的一个。

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
def r_sum(mylist,nsum=0):
    for i in mylist:
        if isinstance(i,int):
            nsum += i
        else:
            nsum += r_sum(i)
    return nsum
# 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM