2014-02-25 113 views
0

這是我現在的版本的代碼,我不斷收到列表索引錯誤。Python列表索引錯誤

n = 0 
y = len(list1)-1 
while n < y: 
    for k in list1: 
     if list1[n]+ k == g: 
      print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".") 
      break 
     else: 
      n = n+1 
+0

什麼樣的列表索引錯誤?哪裏?什麼是確切的錯誤信息? – Kevin

+0

if list1 [n] + k == g: IndexError:列表索引超出範圍 – user3349164

+0

它是什麼行? – Kevin

回答

2

您在for循環遞增n但在外部while循環測試其contraint。

也許這就是你想要的東西:

n = 0 
y = len(list1)-1 
found = 0 
while n < y: 
    for k in list1: 
     if list1[n]+ k == g: 
      print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".") 
      found = 1 
      break # for loop 
    if found: 
     break # while loop 
    n = n + 1 

一個更好的辦法做到這一點是使用itertools.combinations_with_replacement

import itertools 
for (v1,v2) in itertools.combinations_with_replacement(list1, 2): 
    if v1 + v2 == g: 
     print("blah blah blah") 
     break 

combinations_with_replacement(list1,2)將返回list1兩種元素的所有無序組合。例如,combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC

+0

謝謝你,但錯誤仍在等待中: – user3349164

+0

主 如果list1 [n] + k == g: IndexError:列表索引超出範圍 – user3349164

+0

我現在看到了,謝謝你哦!我認爲循環現在起作用 – user3349164

0

您留下了一些信息,但我收集到您正在嘗試查找與目標相匹配的2個素數。爲了以這種方式訪問​​列表,您需要枚舉它。

y = len(list1) - 1 
while n < y: 
    for n, k in enumerate(list1): 
     if list1[n]+ k == g : 
      print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".") 
      break 

但是,你並不真的需要索引,兩個for循環會完成同樣的事情。

target = 8 
primes = [2, 3, 5, 7, 11, 13, 17, 19] 
message = 'The 2 prime numbers that add up to {target} are {value1} and {value2}' 
for index1, value1 in enumerate(primes): 
    for value2 in primes[index1 + 1:]: 
     if value1 + value2 == target: 
      print(message.format(target=target, value1=value1, value2=value2))