首页 > 解决方案 > 列表列表 | 将子元素相乘,添加答案(Python)

问题描述

非常感谢所有帮助回答的人。这些都按应有的方式工作,并且是可附加的。如下所示。

我想打印乘法和加法。

import numpy as np

# [x, w] including bias
X = [[0.5, 0.15], [0.1, -0.3], [1, 0]]

in_str = 'in = '
for input in X:
  substr = '('+str(input[0])+' x '+str(input[1])+') + '
  in_str += substr
in_str = in_str[:-3]
print(in_str)

calcs = [x * y for x, y in X]
in_str = '   = '
for c in calcs:
  substr = '('+str(c)+') + '
  in_str += substr
in_str = in_str[:-3]
print(in_str)

ans = sum([x * y for x, y in X])
print('   = ' + str(ans))

输出:

in = (0.5 x 0.15) + (0.1 x -0.3) + (1 x 0)
   = (0.075) + (-0.03) + (0)
   = 0.045

标签: pythonlistprintingmultiplication

解决方案


使用列表理解:

ans=sum([x*y for x,y in X])

推荐阅读