我试图获得向量的加权和(vect的维度是可变的),数据为:
vect[1] = [5., 6., 7.] mult[1][1] = "20"
vect[2] = [7., 8., 9.] mult[2][1] = "80"
......
我在寻找的是:
\sum(vect[i]*float(mult[i][1]))
但是,我无法理解。
具体例子:
print(vect)
for i in range(2):
print(mult[i][1])
lat_alloy = [3]
for i in range(len(m)):
nvect[i] = vect[i]*float(mult[i][1])
lat_alloy[1] = sum(item[1] for item in nvect)
lat_alloy[2] = sum(item[2] for item in nvect)
lat_alloy[3] = sum(item[3] for item in nvect)
print(lat_alloy)
我很早就失败了:
[[286.65, 286.65, 286.65], [250.71, 250.71, 406.95]]
20
80
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/ptbl/veggards.py", line 68, in entry_text
nvect[i] = vect[i]*float(mult[i][1])
TypeError: can't multiply sequence by non-int of type 'float'
我想要的是:
[286.65, 286.65, 286.65]*20
+ + +
[250.71, 250.71, 406.95]*80
请帮助。
答案 0 :(得分:1)
因为我的代码的某些其他部分出了问题,所以我也改变了其他部分:
# These were my inputs
vect = [[286.65, 286.65, 286.65], [250.71, 250.71, 406.95]]
mult = [[0,20],[0,80]]
lat_alloy = []
for i in range(len(vect)):
lat_alloy.append([j * float(mult[i][1]) for j in vect[i]])
results = []
for i in range(len(lat_alloy[0])):
results.append(sum([j[i] for j in lat_alloy]))
print(results)
或者如果你想要一些非常简洁但不清楚的代码:
lat_alloy = [([j * float(mult[i][1]) for j in vect[i]]) for i in range(len(vect))]
results = [(sum([j[i] for j in lat_alloy])) for i in range(len(lat_alloy[0]))]
print(results)
两个输出:
20
80
[25789.8, 25789.8, 38289.0]