【问题标题】:Writing a function which has bisect_left as part of it to accept iteration inputs编写一个以 bisect_left 作为其一部分的函数来接受迭代输入
【发布时间】:2013-03-14 04:25:48
【问题描述】:

我在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 提供的。我怎么解决这个问题? 谢谢。

【问题讨论】:

    标签: python function matplotlib iteration range


    【解决方案1】:

    您的代码实际上可以正常工作,但是我给出了一些 cmets:

    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,10,100),您正在创建一个 numpy 数组(scipy 从 numpy 导入 linspace),它内置了对矢量化计算的支持。 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
    

    【讨论】:

    • 实际上在我的真实代码中我使用了 np.在这里,当我给出示例时,我忘记了,但非常感谢。但它仍然不起作用,这是我得到的错误:ValueError:具有多个元素的数组的真值是不明确的。使用 a.any() 或 a.all()
    • 哦!我刚刚意识到为什么会出现这个错误,那是因为我的代码中有 bisec_l​​eft!
    • 我根据新信息编辑了我的问题,但再次感谢
    • 我不太明白你想从你的问题中做什么。你确定你的例子是正确的吗? bisect 的 numpy 替代品应该是 numpy.searchsorted
    【解决方案2】:

    您可以使用生成器表达式plt.plot(t, (sqr(x) for x in t))
    编辑:您也可以输入函数:

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

    或者你可以写一个Generator 和yield 声明:

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

    【讨论】:

    • 谢谢,但我仍然希望编写 python 函数的方式来实现它作为函数的一部分,而不是在情节中这样做
    • -1 因为 OP 使用 scipy.linspace 生成一个 numpy 数组,因此您不需要任何迭代或生成器表达式,但您可以使用内置功能。
    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    相关资源
    最近更新 更多