2013-03-14 47 views
0

我已經用Python編寫的函數如下功能:寫作已bisect_left作爲它的一部分接受重複輸入

from bisect import basect_left 
    def find(i): 
     a=[1,2,3] 
     return bisect_left(a,i); 

我想這個函數接受迭代作爲輸入,併產生重複的輸出。特別是我與numpy的工作,我希望能夠用linspace作爲輸入和 得到輸出此代碼:

import matplotlib.pyplot as plt 
t=scipy.linspace(0,10,100) 
plt.plot(t,find(t)) 

更新!!!: 我意識到我的錯誤是:

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

這是從bisect庫給出的bisect_left。我怎麼解決這個問題? 謝謝。

回答

0

您可以使用生成器表達式plt.plot(t, (sqr(x) for x in t))
編輯:你可以把在功能以及:

def sqr(t): 
    return (i*i for i in t); 

或者你可以寫一個Generator與產量聲明:

def sqr(t): 
    for i in t: 
     yield i*i 
+0

謝謝你,但我還是想的是Python函數都寫來實現它的功能的一部分不這樣做在情節的方式 – Cupitor 2013-03-14 04:33:58

+0

@Naji編輯了答案 – Igonato 2013-03-14 04:46:41

+0

-1,因爲OP使用'scipy.linspace'創建了一個numpy數組,因此您不需要任何迭代或生成器表達式,但是可以使用內置的特性。 – bmu 2013-03-14 06:19:15

1

你代碼實際上可以正常工作,但我給出了一些意見:

def sqr(i): 
    return i*i;      # you don't need the ";" here 

import matplotlib.pyplot as plt 
import scipy      # you should use "import numpy as np" here 
t=scipy.linspace(0,10,100)   # this would be "np.linspace(...)" than 
plt.plot(t,sqr(t))     

simple_figure.png

有了您的通話scipy.linspace(0,10,100)您要創建一個numpy的陣列(SciPy的進口linspace從numpy的),它已經內置矢量計算的支持。 Numpy提供矢量化ufuncs,如果您需要更復雜的計算,您可以使用它與indexing一起使用。 Matplolib接受numpy數組作爲輸入並繪製數組中的值。

下面是使用ipython作爲一個互動的控制檯的例子:

In [27]: ar = np.arange(10) 

In [28]: ar 
Out[28]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

In [29]: ar * ar 
Out[29]: array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]) 

In [30]: np.sin(ar) 
Out[30]: 
array([ 0.  , 0.84147098, 0.90929743, 0.14112001, -0.7568025 , 
     -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849]) 
In [31]: ar.mean() 
Out[31]: 4.5 

In [32]: ar[ar > 5] 
Out[32]: array([6, 7, 8, 9]) 

In [33]: ar[(ar > 2) & (ar < 8)].min() 
Out[33]: 3 
+0

其實在我真正的代碼中我使用np。在這裏,當我舉例時,我忘了它,但非常感謝。但仍然不起作用,這是我得到的錯誤: ValueError:具有多個元素的數組的真值是不明確的。使用a.any()或a.all() – Cupitor 2013-03-14 10:44:28

+0

OH!我剛剛意識到爲什麼會出現這種錯誤,那是因爲我的代碼中有bisec_l​​eft! – Cupitor 2013-03-14 10:55:20

+0

我根據新信息編輯我的問題,但再次感謝 – Cupitor 2013-03-14 10:56:58

相關問題