【问题标题】:Class n dimensional vectorn 类维向量
【发布时间】:2022-12-17 07:17:09
【问题描述】:

我知道如何为 2n 向量实现一个类。

class vect:
    def __init__(self, *a):
        self.a = a
    def plus(self, *plus):
        res_plus = [vi + wi for vi, wi in zip(self.a, plus)]
        return res_plus
    def minus(self, *minus):
        res_minus = [vi - wi for vi, wi in zip(self.a, minus)]
        return res_minus
    def multiply(self, mult):
        res_multiply = [mult * vi for vi in self.a]
        return res_multiply
x = vect(1,2,3)
print('plus:', x.plus(3,2,1))

它工作正常 加上:[4, 4, 4]

但是随着

x = vect([1,2,3])
print('plus:', x.plus([3,2,1]))

我得到加号:[[1, 2, 3, 3, 2, 1]]

如何解决这个问题

def convert(list):
    return (*list, )

【问题讨论】:

  • 那么问题是什么?你能指望什么?
  • 如果从 init 中删除 *,则加上和减去。例如__init__(self, a),然后x = vect([1,2,3]) print('plus:', x.plus([3,2,1])) 就可以了。 *list 表示您传递的是参数列表而不是列表(您在第二个示例中正在这样做)

标签: python oop vector


【解决方案1】:

我觉得你很困惑参数列表加星标的表达概念。

如果您不想更改代码,请在调用函数时使用解包/星号表达式:

x = vect(*[1,2,3]) # This syntax means: take the list and pass it as three separate postitional arguments
# So it's literally the same as doing
x = vect(1,2,3)
print('plus:', x.plus(*[3,2,1]))

看看这个例子:

class A:
   def __init__(self, *a):
      self.a = a # This is going to be a tuple

first = A(1,2,3)
first.a # (1,2,3) three element tuple
second = A([1,2,3]
second.a # ([1,2,3],) one element tuple with a list as the 1st item
third = A([1,2,3], 4)
third.a # ([1,2,3], 4) two element tuple with list as the 1st item and int 4 as 2nd item

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2013-07-19
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多