[英]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.