【问题标题】:Plotting a lambda with embedded if statement in Python using pyplot使用 pyplot 在 Python 中使用嵌入式 if 语句绘制 lambda
【发布时间】:2016-05-13 04:45:27
【问题描述】:

我想做这样的事情:

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:具有多个元素的数组的真值是 模糊的。使用 a.any() 或 a.all()

另一方面,我能够做到:

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

1.0 0.5

为什么会这样,有解决办法吗?

【问题讨论】:

    标签: python matplotlib lambda


    【解决方案1】:

    Python 列表不允许您对列表进行比较。因此,例如,您不能执行 range(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()
    

    【讨论】:

      【解决方案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>]
      

      【讨论】:

        猜你喜欢
        • 2022-11-26
        • 1970-01-01
        • 1970-01-01
        • 2015-06-20
        • 2023-04-08
        • 2018-02-28
        • 2023-01-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多