2016-01-22 29 views
2

當計算數組每個值的絕對值時,我得到一個與abs():'list'的壞操作數類型相關的錯誤。源代碼中出現故障的部分是下一個:abs()的壞操作數類型:'list'

x = amplitudex * sin((2 * pi * (frequency * 1) * t) + phase); 
y = amplitudey * sin((2 * pi * (frequency * 2) * t) + phase); 
z = amplitudez * sin((2 * pi * (frequency * 3) * t) + phase); 

w= 0.55* (x + y + z); 
.... 
n = len(w); 
wf = [float(0)] * n; 
for k in range(n): # For each output element 
    s = float(0); 
    for t in range(n): # For each input element 
     s += w[t] * cmath.exp(-2j * cmath.pi * t * k/n); 
    wf[k] = float(s); 

sf = np.linspace(0.0, 1.0/(2.0*numCycles), numSamples/2); 

#The calculation of absolute values causes error: 
plot(sf, 2.0/numSamples * abs(wf[0:100])); 

如何在abs函數中修復此錯誤?我得到這個錯誤:(迷茫

感謝

+0

因爲'abs'不能爲了適用於ABS每個元素的數組 –

+0

使用'map';'。 –

+1

中您可以結束只是一個新行語句,沒有'被澆鑄爲列表 – TigerhawkT3

回答

2

據我瞭解,你想abs與其他一些計算以及應用於列表切片中的每個成員,因爲你使用切片表示法。這很容易與list comprehension

plot(sf, [2.0/numSamples * abs(element) for element in wf[0:100]]); 
0

您,是因爲abs不能用於list錯誤你可以用地圖使用它。

map(abs, wf[0:100]) 

如果你正在使用Python 3添加list

list(map(abs, wf[0:100])) 

或者你可以使用list comprehension設置你的abs_list:

wf_abs = [abs(x) for x in wf[0:100]] 
4

我看到你已經輸入了numpy,因爲你在代碼中使用np.linspace。你可能會混淆numpy的abs,它會很高興在列表和數組上工作,__builtin__.abs,它只適用於標量。

更改此:

abs(wf[0:100]) 

要這樣:

np.abs(wf[0:100]) 
相關問題