小编Ken*_*das的帖子

复制Python int*numpy.array行为

我正在尝试使用大多数正常的数学运算来构建矩阵的类表示.我用标量乘法运算遇到了麻烦.

代码的相关部分如下:

import numpy

class Matrix(object):

    def __init__(self, array):
        self.array = numpy.array(array, dtype=int)

    def __mul__(self, other):
        if type(other) == int:
            return Matrix(other*self.array)
        else:
            raise ValueError("Can not multiply a matrix with {0}".format(type(other)))
Run Code Online (Sandbox Code Playgroud)

标量乘法表示的标准方法是cA,其中c是标量,A是矩阵,因此c*A在Python中.但是,这会因为预期的运行TypeError: unsupported operand type(s) for *: 'int' and 'Matrix'而失败A*c(请注意other*self.array).因此我得出结论,*操作数是为int和定义的numpy.array.

这是什么魔法,我怎样才能复制这种行为?

python numpy

3
推荐指数
1
解决办法
28
查看次数

Python ValueError:解包的值太多(预期为 2)

输入

 2 4
 1 2 3 4
 1 0
 2 1
 2 3  
Run Code Online (Sandbox Code Playgroud)

我需要从第三行提取数字对到最后(第三行只有 2 个数字)
这是我的功能

def read_nodes():
    n, r = map(int, input().split())
    n_list = []

    for i in range(2 , n):
        n1, n2 = map(int, input().split())
        n_list.append([n1, n2])
    return n_list
print(read_nodes())
Run Code Online (Sandbox Code Playgroud)

我除了[[1,0],[2,1],[2,3]] 但说 ValueError: too many values to unpack (expected 2)

python

2
推荐指数
2
解决办法
2万
查看次数

标签 统计

python ×2

numpy ×1