【问题标题】:How to add two arrays in numpy如何在numpy中添加两个数组
【发布时间】:2019-10-13 19:42:17
【问题描述】:

这是一个示例代码,我想添加两个数组的元素。我已经导入了 NumPy,不想导入数组。

from numpy import *

a = array([])
b = array([])
c = array([])

d = input("Enter the length of the arrays")
print ("Enter the elements of array 1")
for i in range(d):
    append(a, int(input("Enter the element ")))
print ("Enter the elements of array 2")
for i in range(d):
    append(b, int(input("Enter the element ")))

for i in range(1, d+1):
    append(c, (a[i] + b[i]))

print(a)
print(b)
print(c)

预期的输出应该是数组元素的总和,但我得到以下错误:

IndexError:索引 1 超出轴 0 的范围,大小为 0

【问题讨论】:

  • 范围不应该从 0 到 d 吗?
  • 与问题无关,但我认为它可能有用:鉴于您如何使用 abc,您可能应该在此处使用 list 而不是numpy.array。数组是固定大小的,所以 numpy.append 必须复制完整的数组,而列表是可变大小的,list.append 很少需要复制列表。

标签: python numpy


【解决方案1】:

首先您需要将d 转换为int

d = int(input("Enter the length of the arrays"))

之后,您应该将append 函数的结果分配给array

print ("Enter the elements of array 1")
for i in range(d):
    a = append(a, int(input("Enter the element ")))
print ("Enter the elements of array 2")
for i in range(d):
    b = append(b, int(input("Enter the element ")))

那么结果就好了

【讨论】:

    【解决方案2】:

    函数append 不会改变其参数的状态。相反,它返回添加了元素的数组。

    所以要将元素添加到数组中,您需要:a = append(a, 2)

    同样在 NumPy 中,您可以使用 add(a,b) 对两个数组求和。

    如果我们将所有这些应用到您的示例中,我们会得到:

    from numpy import *
    
    a = array([])
    b = array([])
    c = array([])
    
    d = input("Enter the length of the arrays")
    print ("Enter the elements of array 1")
    for i in range(d):
        a = append(a, int(input("Enter the element ")))
    print ("Enter the elements of array 2")
    for i in range(d):
        b = append(b, int(input("Enter the element ")))
    
    c = add(a, b)
    
    print(a)
    print(b)
    print(c)
    

    【讨论】:

    • 只是出于好奇,如果我想使用 for 循环而不是 inbult add() 函数,那我该怎么办? @dmigo
    • 你应该选择for i in range(d): c = append(c, (a[i] + b[i]))
    猜你喜欢
    • 2012-11-24
    • 1970-01-01
    • 2016-01-21
    • 2015-04-09
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    相关资源
    最近更新 更多