【问题标题】:Python: Applying arithmetic operators on list like on numpy.ndarray?Python:在 numpy.ndarray 上的列表上应用算术运算符?
【发布时间】:2020-07-13 00:04:08
【问题描述】:

这是我的第一个代码,使用 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 中完成的,以自动迭代列表?

【问题讨论】:

  • 错误是什么?
  • Traceback(最近一次调用最后):文件“C:/Users/QINY/PycharmProjects/begin/covid/seven.py”,第 24 行,在 graph(my_formula, "2 * (x ** 3) - 9.5 * (x ** 2) + 10.5 * x", 0, 3) 文件“C:/Users/QINY/PycharmProjects/begin/covid/seven.py”,第 16 行,在图中y = 公式(字符串,x)文件“C:/Users/QINY/PycharmProjects/begin/covid/seven.py”,第 21 行,在 my_formula 返回 eval(字符串)文件“”,第 1 行,在 TypeError: ** 或 pow() 不支持的操作数类型:'list' 和 'int'
  • 好的,你到底在问什么? “如何实现列表迭代”是什么意思?这个例子对于我认为你要问的问题来说完全过于复杂了。
  • 如果您不关心元素的迭代顺序,您可以使用 nditer 遍历数组对象::docs.scipy.org/doc/numpy/reference/arrays.nditer.html

标签: python numpy iteration numpy-ndarray


【解决方案1】:

他们使用Standard operators as functions

它们的类型支持__pow____mul____add__ 等函数,其实现将操作应用于ndarray 的每个元素(非常有效...)

您可以创建自己的继承自 list 的类型,并让它实现这些成员函数,自己迭代列表,将其应用于每个元素。

【讨论】:

  • class Iteration: def __init__(self, array): self.array = array def __pow__(self, power, modulo=None): new_array = list() for i in self.array: new_array.append(i ** power) return new_array def __len__(self): return len(self.array) def __getitem__(self, indices): return self.array[indices]
  • it = Iteration([1, 2, 3]) def sub(list1, list2): new_list = list() for i, d in enumerate(list1): new_list.append(d - list2[i]) return new_list print(sub([6, 7, 8], it)) #=&gt; [5, 5, 5]
猜你喜欢
  • 2019-03-04
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 2018-10-16
  • 1970-01-01
  • 2019-08-02
相关资源
最近更新 更多