vector减法我正在使用python 3.5

时间:2017-02-19 23:18:58

标签: python

def vector_subtract(v, w):          
    """subtracts two vectors componentwise"""         
    return [v_i - w_i for v_i, w_i in zip(v, w)] 

我收到此错误

TypeError: unsupported operand type(s) for -: 'dict' and 'dict'

4 个答案:

答案 0 :(得分:0)

这是如何减去矢量。

vector1 = [[1, 1], [1, 1], [1, 1], [1, 1], [1, 1]]
vector2 = [[1, 1], [1, 1], [1, 1], [1, 1], [1, 1]]

def subVector(vec1, vec2):
    return [[vec2[0] - vec1[0], vec2[1] - vec1[1]] for vec1, vec2 in zip(vec1, vec2)] 

print(subVector(vector1, vector2))

给出了:

[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]

我认为这就是你要做的事情。

答案 1 :(得分:0)

我建议使用魔术方法,而不是创建自定义减法功能。例如,这就是int和str对象覆盖 __ add __()函数的方式......

# this is how the int object does it...
a = 1
b = 2

# a + b = 3

# and this is how the str object does it...
c = "hello"
d = "world"

# c + d = "helloworld"

请注意,在这两种情况下,都使用相同的运算符,但结果不同,具体取决于对象如何覆盖 add ()魔术方法。

您可以通过创建Vector类并覆盖 __ sub __()魔术方法来利用魔法方法的强大功能。

例如,这是一个简单的Vec3类:

class Vec3():
    def __init__(x, y, z):
        self.x, self.y, self.z = x, y, z

    """
    Can be called simply like v - w, if v and w are Vector's.
    :param other:  Another Vector to be subracted to self.
    :return: The difference of the two vectors.
    """
    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y, self.z - other.z)

这样,我们可以创建许多Vec3实例......

vec3_a = Vec3(4,5,6)
vec3_b = Vec3(1,2,3)

并使用" - "减去它们。操作

vec3_diff = vec3_a - vec3_b

答案 2 :(得分:0)

@JJ_Shakur,这是一个通用矢量类的可能解决方案:

import numpy as np

class Vector:
    def __init__(self, *args):
        self.elms = np.array(args)

    def __sub__(self, other):
        self.elms.resize(other.elms.shape) if len(self.elms) < len(other.elms) \
                                           else other.elms.resize(self.elms.shape)
        return Vector(*(self.elms - other.elms))

    def __getitem__(self, index):
        return self.elms[index]

    def __len__(self):
        return len(self.elms)

    def __str__(self):
        return str(self.elms)

'''
The main function
'''
if __name__ == "__main__":
    v1 = Vector(0.6,0.3,0.5,1.0)
    v2 = Vector(1.0,1.0,0.5)

    print('sub: {}'.format(v1 - v2))

答案 3 :(得分:0)

您可以创建自己的Vector类

class Vector:

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z


    def print_axes(self):
        return self.x, self.y, self.z


    def sub(self, vec_s):
        self.x -= vec_s.x
        self.y -= vec_s.y
        self.z -= vec_s.z

在主文件中:

robot1 = Vector(float(1.0), float(2.0), float(3.0))
robot2 = Vector(float(2.0), float(2.0), float(2.0))

robot1.sub(robot2)

print(robot1.print_axes())

控制台结果

(1.0, 2.0, 3.0)          
(-1.0, 0.0, 1.0)