2016-02-03 41 views
1

嵌入我想要做這樣的事情:繪製拉姆達與如果在Python語句中使用pyplot

import numpy as np 
import matplotlib.pyplot as plt 
xpts = np.linspace(0, 100, 1000) 
test = lambda x: 0.5 if x > 66 else 1.0 
plt.plot(xpts, test(xpts)) 

,但我得到的錯誤:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

在另一方面,我能要做到:

print(test(50), test(70)) 

1.0 0.5

這是怎麼回事有沒有解決方案?

回答

2

您不能將數組轉換爲bool如果它包含多個元素:

In [21]: bool(np.array([1])) 
Out[21]: True 

In [22]: bool(np.array([1, 2])) 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-22-5ba97928842c> in <module>() 
----> 1 bool(np.array([1, 2])) 

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

你,或許,想申請test功能的陣列中的每個元素:

In [23]: plt.plot(xpts, [test(x) for x in xpts]) 
Out[23]: [<matplotlib.lines.Line2D at 0x7fa560efeeb8>] 

你也可能會創建函數的矢量化版本,並將其應用於陣列,而無需列表理解:

In [24]: test_v = np.vectorize(test) 

In [25]: plt.plot(xpts, test_v(xpts)) 
Out[25]: [<matplotlib.lines.Line2D at 0x7fa560f19080>] 
1

Python列表不允許您執行列表比較。所以你不能,例如,做範圍(10)> 10.相反,你可以將輸入轉換爲一個numpy數組並執行範圍檢查。 T

import numpy as np 
import matplotlib.pyplot as plt 
xpts = np.linspace(0, 100, 1000) 
test = lambda x: (np.array(x) <= 66)*.5 + .5 
print xpts, test(xpts) 
plt.plot(xpts, test(xpts)) 
plt.show()