python-2.7 - 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)
解决方案
这是你想要的?
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)
推荐阅读
- apache-kafka - 无法配置 AWS Lambda 和 AWS Kafka(MSK 集群)之间的跨账户通信
- python - 质心跟踪,如何正确进行排序?
- json - Flutter andoid emulator 使用 path_provider 将文件保存到 Windows 本地磁盘在哪里?
- flutter - Flutter Web 项目不适用于托管
- node.js - 向 iOS 发送推送通知的问题,(云功能)
- bash - 回显名称不是数字,以防万一(选择)。#bash
- java - 对箭头文件进行零拷贝读取的 Java 方法?
- javascript - 文件上传开始时停止
- javascript - 在 EJS 中循环 JSON 以创建表
- c - 如何在 C 中输入输入运算符?