2013-04-06 112 views
3

我需要添加兩個數字列表。當一個列表大於另一個時,我得到錯誤「IndexError:列表索引超出範圍」。該錯誤發生在resultado = v1[i] + v2[i]行,但我不知道如何解決它。如何總結兩個列表N元素

我的代碼是:

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 

回答

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)] 
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) 
+1

+1實際幫助OP – georg 2013-04-06 23:00:00

相關問題