TypeError: zip argument #1 must support iteration (Vector sum for Ipython)

TypeError: zip argument #1 must support iteration (Vector sum for Ipython)

您好,我正在关注 "Data Science from Scratch",但我在制作矢量求和函数时遇到错误。有人可以帮忙吗?

代码:

a = [1,2,3]
b = [2,3,4]

def vector_add(v, w):
    """adds two vectors componentwise"""
    return [v_i + w_i for v_i, w_i in zip(v,w)]
vector_add(a,b) #prints [3, 5, 7]

def vector_sum(vectors):
    result = vectors[0]
    for vector in vectors[1:]:
        result = vector_add(result, vector)     
    return result
vector_sum(a)

错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-41-401c63999247> in <module>()
      4         result = vector_add(result, vector)
      5     return result
----> 6 vector_sum(a)

<ipython-input-41-401c63999247> in vector_sum(vectors)
      2     result = vectors[0]
      3     for vector in vectors[1:]:
----> 4         result = vector_add(result, vector)
      5     return result
      6 vector_sum(a)

<ipython-input-15-502c43cd9568> in vector_add(v, w)
      4 def vector_add(v, w):
      5     """adds two vectors componentwise"""
----> 6     return [v_i + w_i for v_i, w_i in zip(v,w)]
      7 vector_add(a,b)

TypeError: zip argument #1 must support iteration

如果你这样做 vector_sum(a) 局部变量 result 将是你第一步中不可迭代的整数“1”。所以我想你应该简单地调用你的函数 vector_sum like

vector_sum([a,b,a])

求和多个向量。后者在我的机器上给出 [4,7,10]

如果您想对一个向量的分量求和,则不应使用 vector_add 函数。