[英]Python: Applying arithmetic operators on list like on numpy.ndarray?
这是我的第一个代码,使用 numpy.linspace 方法:
import numpy as np
import matplotlib.pyplot as plt
def graph(formula, string, x1, x2):
x = np.linspace(x1, x2)
y = formula(string, x)
plt.plot(x, y)
def my_formula(string, x):
return eval(string)
graph(my_formula, "2 * (x ** 3) - 9.5 * (x ** 2) + 10.5 * x", 0, 3)
plt.tight_layout()
plt.show()
但是,如果我这样做,它可以正常工作,而不是导入 numpy:
import matplotlib.pyplot as plt
class Module:
@staticmethod
def linspace(finish, slices, start=0):
each = float((finish - start) / (slices - 1))
res = list()
for i in range(slices):
res.append(start + i * each)
return res
def graph(formula, string, x1, x2):
x = Module.linspace(x2, 50, start=x1)
y = formula(string, x)
plt.plot(x, y)
def my_formula(string, x):
return eval(string)
graph(my_formula, "2 * (x ** 3) - 9.5 * (x ** 2) + 10.5 * x", 0, 3)
plt.tight_layout()
plt.show()
这是一个错误显示:
Traceback (most recent call last):
File "C:/Users/QINY/PycharmProjects/begin/covid/seven.py", line 24, in <module> graph(my_formula, "2 * (x ** 3) - 9.5 * (x ** 2) + 10.5 * x", 0, 3)
File "C:/Users/QINY/PycharmProjects/begin/covid/seven.py", line 16, in graph y = formula(string, x) File "C:/Users/QINY/PycharmProjects/begin/covid/seven.py", line 21, in my_formula return eval(string)
File "<string>", line 1, in <module> TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
谁能解释一下它是如何在 numpy.adarray 中完成的,以自动迭代列表?
他们使用标准运算符作为函数。
它们的类型支持诸如__pow__
、 __mul__
、 __add__
等函数......以及在ndarray
每个元素上应用操作的ndarray
(非常有效......)
您可以创建自己的继承自list
的类型,并让它实现这些成员函数,自己迭代列表,将其应用于每个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.