简体   繁体   中英

Python: Applying arithmetic operators on list like on numpy.ndarray?

here's my first code, using numpy.linspace method:

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()

it works fine, however, instead of importing numpy, if I do this:

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()

Here's a error shows up:

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'

Can anyone explain how it is done in numpy.adarray, to automatically iterate the list?

They use Standard operators as functions .

Their type supports functions like __pow__ , __mul__ , __add__ , etc... with implementations that apply the operations on each element of the ndarray (very efficiently...)

You can make your own type that inherits from list and have it implement these member functions, iterating the list yourself, applying it on every element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM