1
我有這樣的代碼片段:numpy的數組:價值分配失敗
import numpy as np
a=np.array([5,6,7,8,9])
b=np.array([5,6,7,8,9])
scoreA = np.array([float(1)/(i + 1) for i in range(len(a))])
scoreB = np.array([0 for i in range(len(b))])
for eleA in a:
if eleA in b:
i, = np.where(b == eleA)
i = i[0]
j, = np.where(a == eleA)
j = j[0]
scoreB[i] = scoreA[j]
print "B is: %f" % scoreB[i]
print "A is: %f" % scoreA[j]
所以其基本思路是:對數組a和b,如果一個元素在他們兩人發現,然後我會分配scoreA中的元素得分爲B。但結果是這樣的:
B is: 1.000000
A is: 1.000000
B is: 0.000000
A is: 0.500000
B is: 0.000000
A is: 0.333333
B is: 0.000000
A is: 0.250000
B is: 0.000000
A is: 0.200000
這意味着該行:
scoreB[i] = scoreA[j]
工作不正常?我該如何解決這個問題?
IIUC,只要:'mask = a == b'; 'scoreB [mask] = scoreA [mask]'。 – Divakar