简体   繁体   English

如何在Python的列表列表中添加所有项目

[英]How to add all items in a list of lists in Python

I was trying to make a definition that would add all numbers within each sublist in a list of lists. 我试图做出一个定义,将所有数字添加到列表列表中的每个子列表中。

def MassAddition(_list):
    output = []
    total = 0
    for i in _list:
        if isinstance(i, list):
            output.append(MassAddition(i))
        else:
            total = total + i
    output.append(total)
    return output

Problem is that it returns an extra item in a list at the end. 问题在于,它最后在列表中返回了一个额外的项目。 I think its because I made total = 0 and then appended it to output list outside of for loop. 我认为这是因为我使total = 0,然后将其附加到for循环之外的输出列表中。 Can someone help me clean this up? 有人可以帮我清理吗? Ps. PS。 This definition should be able to handle any level of nested lists. 该定义应该能够处理任何级别的嵌套列表。

example: input = [[0,1,2], [2,1,5],[2,2,2],2,2,1] desiredoutput = [[3],[8],[6],5] 示例: input = [[0,1,2], [2,1,5],[2,2,2],2,2,1] desiredoutput = [[3],[8],[6],5]

Thank you, 谢谢,

You can check the additional numbers for type too. 您也可以检查其他数字的类型。 If they can only be int : 如果它们只能是int

def mass_addition(lst):
    output = []
    total = 0
    extra_flag = False
    for i in lst:
        if isinstance(i, list):
            output.append(mass_addition(i))
        elif isinstance(i, int):
            extra_flag = True
            total += i
    if extra_flag:
        output.append(total)
    return output

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

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