2013-10-02 31 views
2

所以在這裏我有x1vals:如何從Python矢量的特定索引列表中選擇組件?

>>> x1Vals 
[-0.33042515829906227, -0.1085082739900165, 0.93708611747433213, -0.19289496973017362, -0.94365384912207761, 0.43385903975568652, -0.46061140566051262, 0.82767432358782367, -0.24257307936591843, -0.1182761514447952, -0.29794617763330011, -0.87410892638408, -0.34732294121174467, 0.40646145339571249, -0.64082861589870865, -0.45680189916940073, 0.4688889876175073, -0.89399689430691298, 0.53549621114138612] 

這裏就是我要選擇

>>> np.where(np.dot(XValsOnly,newweights) > 0) 

>>>(array([ 1, 2, 4, 5, 6, 8, 9, 13, 15, 16]),) 

但x1Vals指數的列表時,我試圖讓x1Vals的值Matlab的方式,我得到這個錯誤:

>>> x1Vals[np.where(np.dot(XValsOnly,newweights) > 0)] 

Traceback (most recent call last): 
    File "<pyshell#69>", line 1, in <module> 
    x1Vals[np.where(np.dot(XValsOnly,newweights) > 0)] 
TypeError: list indices must be integers, not tuple 
>>> np.where(np.dot(XValsOnly,newweights) > 0) 

有沒有辦法解決這個問題?

回答

1

問題是您的x1Valslist對象,它不支持花哨的索引。你只需要建立一個陣列:

x1Vals = np.array(x1Vals) 

和你的方法將工作。

更快的方法將是使用np.take

np.take(x1Vals, np.where(np.dot(XValsOnly,newweights) > 0)) 
+0

或更簡單和速度甚至比'take','x1Vals [np.dot(XValsOnly,newweights)> 0]'。另外,在這裏,'take'返回形狀'(1,N)'而不是'(N,)'。 – askewchan

相關問題