首页 > 解决方案 > inegers 列表的嵌套列表 - 进行算术运算

问题描述

我有一个如下列表,需要先在每个列表中添加项目,然后将所有结果相乘 2+4 = 6 , 3+ (-2)=1, 2+3+2=7, -7+1=-6然后 6*1*7*(-6) = -252 我知道如何通过访问索引来做到这一点并且它可以工作(如下所示)但我还需要以一种不管有多少子列表都可以工作的方式来做是

nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
a= nested_lst[0][0] + nested_lst[0][1]
b= nested_lst[1][0] + nested_lst[1][1]
c= nested_lst[2][0] + nested_lst[2][1] + nested_lst[2][2]
d= nested_lst[3][0] + nested_lst[3][1]

def sum_then_product(list):
    multip= a*b*c*d
    return multip
print sum_then_product(nested_lst)

我尝试过使用 for 循环,它给了我加法,但我不知道如何在这里执行乘法。我是新手。请帮忙

nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
for i in nested_lst:
    print sum(i)

标签: python-2.7

解决方案


这是你想要的?

nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]] # your list
output = 1 # this will generate your eventual output

for sublist in nested_lst:
    sublst_out = 0
    for x in sublist:
        sublst_out += x # your addition of the sublist elements
    output *= sublst_out # multiply the sublist-addition with the other sublists
print(output)

推荐阅读