python - 列表列表 | 将子元素相乘,添加答案(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
解决方案
使用列表理解:
ans=sum([x*y for x,y in X])
推荐阅读
- azure-cosmosdb - Azure cosmos db 在没有分区键的情况下更快
- python - Python sklearn 输入形状错误
- c - 串并联功能
- html - 垂直排列相邻的 DIV,无需强制
- laravel - 自定义 webpack 配置的问题
- pandas - 在 Dataframes 上将 2 列绘制为 2 行,将 1 列绘制为 x 轴
- java - 我收到提到的代码超时错误。需要帮助来优化嵌套循环
- c# - 迁移到 .NET Core 3 后出现“项目 'Web' 必须为配置提供值”错误
- r - 如何不从原始 data.table 中删除列?
- python - 在 pandas 数据框上为产品创建每日价格变化