我需要添加两个数字列表。当一个列表大于另一个列表时,我得到错误“IndexError:list index out of range”。错误发生在行resultado = v1[i] + v2[i]
中,但我不知道如何解决它。
我的代码是:
def suma(A, B):
if len(A) > len(B):
v1 = A
v2 = B
else:
v1 = B
v2 = A
v3 = []
i = 0
for i in range(len(v1)):
resultado = v1[i] + v2[i]
v3.append(resultado)
for j in range(len(v1), len(v2)):
v3.append(v2[j])
return v3
vectorA = []
vectorB = []
x = 1
while x !=0:
print "Ingrese los datos para el primer vector (0 para finalizar)"
x = input("-->>")
if x !=0:
vectorA.append (x)
print "=" * 30
x = 1
while x !=0:
print "Ingrese los datos para el segundo vector (0 para finalizar)"
x = input("-->>")
if x !=0:
vectorB.append (x)
print "=" * 30
print vectorA
print vectorB
print "=" * 30
print "A) SUMA DE VECTORES"
print "=" * 30
suma(vectorA, vectorB)
print suma
答案 0 :(得分:7)
>>> import itertools
>>> A = [1, 2, 3]
>>> B = [10, 11]
>>> [a + b for a, b in itertools.izip_longest(A, B, fillvalue=0)]
[11, 13, 3]
所以,
def suma(A, B):
return [a + b for a, b in itertools.izip_longest(A, B, fillvalue=0)]
答案 1 :(得分:2)
def suma(A, B):
return map(sum, itertools.izip_longest(A,B, fillvalue=0))
答案 2 :(得分:2)
在这个阶段学习Python可以帮助你更多的是:
导致实际错误是因为您使用较长列表的长度来迭代这两个列表。通过更改
可以轻松解决for i in range(len(v1)):
进入
for i in range(len(v2)):
因为v2
是上面比较后的较短列表。你也应该替换
for j in range(len(v1), len(v2)):
v3.append(v2[j])
通过
for j in range(len(v2), len(v1)):
v3.append(v1[j])
因为毕竟len(v2)
小于len(v1)
。最后替换
suma(vectorA, vectorB)
print suma
通过
print suma(vectorA, vectorB)
打印结果。你可以在下面找到工作脚本。
def suma(A, B):
if len(A) > len(B):
v1 = A
v2 = B
else:
v1 = B
v2 = A
v3 = []
i = 0
for i in range(len(v2)):
resultado = v1[i] + v2[i]
v3.append(resultado)
for j in range(len(v2), len(v1)):
v3.append(v1[j])
return v3
vectorA = []
vectorB = []
x = 1
while x !=0:
print "Ingrese los datos para el primer vector (0 para finalizar)"
x = input("-->>")
if x !=0:
vectorA.append (x)
print "=" * 30
x = 1
while x !=0:
print "Ingrese los datos para el segundo vector (0 para finalizar)"
x = input("-->>")
if x !=0:
vectorB.append (x)
print "=" * 30
print vectorA
print vectorB
print "=" * 30
print "A) SUMA DE VECTORES"
print "=" * 30
print suma(vectorA, vectorB)