Python列表索引错误

时间:2014-02-25 01:30:38

标签: 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

2 个答案:

答案 0 :(得分:2)

您正在n循环中递增for,但在外部while循环中测试其约束力。

也许这就是你想要的:

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

答案 1 :(得分: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))