使用pyp在Python中绘制嵌入if语句的lambda

2024-07-05 09:25:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想这样做:

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: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

另一方面,我可以做到:

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

1.0 0.5

为什么会发生这种情况,有没有解决办法?


Tags: lambdatestimportnumpyifplotmatplotlibas