python-3.x 两个不同长度数组的和

kpbwa7wx  于 2022-11-26  发布在  Python
关注(0)|答案(5)|浏览(254)

例如,我有2个阵列

arraya[1,1,1,1,1,1,1]
arrayb[0,1,2]

我想将arrayb连续添加到arraya,如下所示:

arraysum[1,2,3,1,2,3,1]

我该怎么做?

mkshixfv

mkshixfv1#

arraya = [1,1,1,1,1,1,1]
arrayb = [0,1,2]

for i in range(len(arraya)):
    arraya[i] += arrayb[i % len(arrayb)]

print arraya

产生[1, 2, 3, 1, 2, 3, 1]

ckx4rj1h

ckx4rj1h2#

您可以将zip与cycle结合使用:

if arrayb:
    arraysum = [sum(x) for x in zip(cycle(arrayb), arraya)]
else:
    arraysum = arraya
t3irkdon

t3irkdon3#

arraya = [1,1,1,1,1,1,1]
arrayb = [0,1,2]
arraysum = []

i=0

while i in range(len(arraya)):
  arraysum.append(arraya[i] + arrayb[i % len(arrayb)])
  i+=1

print (arraysum)
ss2ws0br

ss2ws0br4#

我希望这可以理解。

from itertools import cycle

def sum_arr(smaller_array, larger_array):
    new_a = []

    for _ in zip(cycle(smaller_array), larger_array): # cycle(0, 1, 2) => 0 1 2 0 1 2 . . .

        new_a.append(sum(_))

    return new_a

a = [1,1,1,1,1,1,1]
b = [0,1,2]

if len(a) < len(b):  # check which one is the smaller and to be repeated
    new_array = sum_arr(a, b)
else:
    new_array = sum_arr(b, a)

print(new_array) # [1, 2, 3, 1, 2, 3, 1]
pwuypxnk

pwuypxnk5#

def Sum():
arrayb = [0,1,2]
arraya = [1,1,1,1,1,1,1]
arraySum = []

counter = 0

for i in range(len(arraya)):
    if i % len(arrayb) == 0:
        counter = 0
    
    arraySum.append(arraya[i] + arrayb[counter])
    counter+=1
return arraySum

相关问题