2014-02-25 117 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))