python - 对嵌套列表值求和的函数?

标签 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()

最佳答案

一般来说,您可以展平列表列表并在展平列表中搜索 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

关于python - 对嵌套列表值求和的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27263186/

相关文章:

c++ - 给定头节点,如何递归地找到链表中的最大项?

python - M2Crypto 的 AES 问题

python - 从 Javascript 到 Python - 了解类、方法和属性的工作原理

python - 根据长度从字符串中删除最后一位数字

python - 如何访问字典 python 中列表中的元素?

c# - 列表未使用 IComparable<T> 排序

python - 有没有1.0是整数的交互式编程语言?

Python:比较列表的语义

java - Chain of Rep. 合适与否

python - 为什么我的递归搜索功能不起作用?