Python 编写一个函数,该函数将对分_作为它的一部分,以接受迭代输入
我用python编写了一个函数,如下所示:Python 编写一个函数,该函数将对分_作为它的一部分,以接受迭代输入,python,function,matplotlib,iteration,range,Python,Function,Matplotlib,Iteration,Range,我用python编写了一个函数,如下所示: 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,10
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\u left
提供。我怎样才能解决这个问题?
谢谢。您可以使用生成器表达式
plt.plot(t,(sqr(x)表示t中的x))
编辑:您也可以在函数中输入:
def sqr(t):
return (i*i for i in t);
或者,您可以编写一个with YILD语句:
def sqr(t):
for i in t:
yield i*i
您的代码实际上是按原样工作的,但是我给出一些评论:
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))
通过调用scipy.linspace(0,10100)可以创建一个numpy数组(scipy从numpy导入linspace),该数组内置了对矢量化计算的支持。
Numpy提供矢量化,如果您需要更复杂的计算,可以将其与一起使用。Matplolib接受numpy数组作为输入,并在数组中绘制值
以下是用作交互式控制台的示例:
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
[27]中的:ar=np.arange(10)
In[28]:ar
Out[28]:数组([0,1,2,3,4,5,6,7,8,9])
In[29]:ar*ar
Out[29]:数组([0,1,4,9,16,25,36,49,64,81])
In[30]:np.sin(ar)
出[30]:
阵列([0,0.84147098,0.90929743,0.14112001,-0.7568025,
-0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])
在[31]中:应收账款平均值()
Out[31]:4.5
In[32]:ar[ar>5]
Out[32]:数组([6,7,8,9])
在[33]中:ar[(ar>2)和(ar<8)].min()
Out[33]:3
谢谢,但我仍然希望python函数作为函数的一部分来实现它,而不是在plot-1中使用scipy.linspace
生成numpy数组,因此不需要任何迭代或生成器表达式,但是你可以使用内置的特性,实际上在我的真实代码中我使用了np。在这里,当我举个例子的时候,我忘了,但非常感谢你们。但它仍然不起作用,这是我得到的错误:ValueError:包含多个元素的数组的真值是不明确的。使用a.any()或a.all()哦!我刚刚意识到为什么会出现这样的错误,这是因为我的代码中留下了bisec_!我根据新信息编辑了我的问题,但谢谢,阿加尼,我真的不明白你想从你的问题中做什么。你确信你的例子是正确的吗?。对分的numpy替代方案应该是