编写一个包含bisect_left函数以接受迭代输入的函数

0 投票
2 回答
751 浏览
提问于 2025-04-17 19:02

我写了一个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,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引起的。我该如何解决这个问题呢?谢谢。

2 个回答

0

你可以使用生成器表达式 plt.plot(t, (sqr(x) for x in t)) 来绘图。
补充:你也可以把它放在一个函数里:

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

或者你可以写一个带有 yield 语句的 生成器

def sqr(t):
   for i in t:
      yield i*i
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是从numpy里引入了linspace这个功能),这个数组可以进行快速的向量计算。Numpy提供了一些叫做向量化的函数(ufuncs),你可以和索引结合使用,这样可以进行更复杂的计算。Matplotlib可以接受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

撰写回答