Add two arrays without using for. Python

前端 未结 4 1114
后悔当初
后悔当初 2021-01-17 06:26

I have these two arrays:

import numpy as np
a = np.array([0, 10, 20])
b = np.array([20, 30, 40, 50])  

I´d like to add both in the followin

4条回答
  •  梦谈多话
    2021-01-17 07:28

    First you need to specify the array type, if you use a constructor like that. For instance for integers, use that:

    a = array("i",[0, 10, 20])       # signed int type
    b = array("i",[20, 30, 40, 50]) 
    

    Them you might want to use while loops with counters, it is more complex than for, but avoids the for loop.

    from array import array
    
    a = array("i",[0, 10, 20])  # signed int
    
    b = array("i",[20, 30, 40, 50]) 
    
    c = array("i",[])
    
    count1 = 0
    
    while count1 < len(a):
       count2 = 0
       while count2 < len(b):
           c.append(a[count1]+b[count2])
           count2 += 1
       count1 += 1
    
    print(c)
    

提交回复
热议问题