具有单个列表元素的列表列表的平方差平方和

时间:2018-11-16 04:24:52

标签: python list iterator sum

我有以下两个列表,并试图获取列表之间的平方差的总和

list = [[20.20458675 17.14946271  2.78568516  5.8363439  14.00318441 11.96825089]
 [ 3.89675236  9.99523907 13.0328716  18.10551237 22.11318234 -0.30354959]]

primary = [0, 1, 0, 0, 0, 1]

result = [x, y]

x is sum of squared difference of each element in list[1] and each element in primary (20.20458675 - 0)**2 + (17.14946271 - 1)**2 + .....
y is sum of squared difference of each element in list[2] and each element in primary (3.89675236 - 0)**2 + (9.99523907 - 1)**2 + ......

我试图做这样的事情:

count = 0
for i in list:
    sum = 0
    count += 1
    for j in range(len(i)):
        sum += (i[j] - primary[j])**2
    result[count] = sum

我最终遇到了列表索引错误,有关如何执行此操作的任何建议:

2 个答案:

答案 0 :(得分:0)

您可以使用numpy做到这一点:

import numpy as np
arrList = np.array(lst) # Don't use 'list' as variable name
arrPri = np.array(primary)
x, y = np.sum((arrList-arrPri)**2, axis=1)
# x:
# array([408.22532574, 260.80514582,   7.76004181,  34.06291012,
#    196.08917362, 120.30252759])
# y:
# array([ 15.18467896,  80.91432593, 169.85574214, 327.80957818,
#    488.9928332 ,   1.69924153])

答案 1 :(得分:0)

listl= [[20.20458675 ,17.14946271 , 2.78568516 , 5.8363439 , 14.00318441 ,11.96825089]
, [ 3.89675236 , 9.99523907, 13.0328716 , 18.10551237, 22.11318234 ,-0.30354959]]

primary = [0, 1, 0, 0, 0, 1]
for i in listl:
    print(sum(map(lambda x:(x[0]-x[1])**2,zip(primary,i))))

输出

1027.2451246961205
1084.4563999396066