列表列表 |乘以子元素,添加答案 (Python)
List of Lists | Multiply sub-elements, Add answers (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])
如果我对你的问题理解正确,你需要附加到最终列表的每个子列表中元素的乘积值和最终列表中所有元素的总和。请找到以下代码。传统方式
multiplier = 1
multiplier_list = []
final_sum = 0
for each_list in X:
for i in range(len(each_list)):
multiplier = multiplier * each_list[i]
#multiplier_list.append(multiplier) #If you need final list
final_sum = final_sum + multiplier
multiplier = 1
#print(multiplier_list)
print(final_sum)
X = [[0.5, 0.15], [0.1, -0.3], [1, 0]] # INPUT HERE
print(f"in X = {X}")
output =""
ans = 0
for input in X:
mul=0
mul = input[0]*input[1]
print(f"{input[0]} x {input[1]} = {mul}")
ans+=mul
output = output+f"{mul} + "
output = output[:-2]
output = output+f" = {ans}"
print(output)
非常感谢大家帮忙解答。这些都按应有的方式工作并且已经是可附加的。如下所示。
我想打印乘法和加法的计算结果。
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])
如果我对你的问题理解正确,你需要附加到最终列表的每个子列表中元素的乘积值和最终列表中所有元素的总和。请找到以下代码。传统方式
multiplier = 1
multiplier_list = []
final_sum = 0
for each_list in X:
for i in range(len(each_list)):
multiplier = multiplier * each_list[i]
#multiplier_list.append(multiplier) #If you need final list
final_sum = final_sum + multiplier
multiplier = 1
#print(multiplier_list)
print(final_sum)
X = [[0.5, 0.15], [0.1, -0.3], [1, 0]] # INPUT HERE
print(f"in X = {X}")
output =""
ans = 0
for input in X:
mul=0
mul = input[0]*input[1]
print(f"{input[0]} x {input[1]} = {mul}")
ans+=mul
output = output+f"{mul} + "
output = output[:-2]
output = output+f" = {ans}"
print(output)