[英]Python List Index Error
Here is my version of the code right now and I keep getting list index error. 这是我现在的代码版本,我不断得到列表索引错误。
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
You are incrementing n
in the for
loop but testing its contraint in the outer while
loop. 您正在for
循环中递增n
,但在外部while
循环中测试其约束。
Perhaps this is what you wanted: 也许这就是你想要的:
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
A much better way to do it is using itertools.combinations_with_replacement
: 更好的方法是使用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)
will return all the unordered combinations of two elements of list1
. combinations_with_replacement(list1,2)
将返回list1
的两个元素的所有无序组合。 For instance, combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
例如, combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
You left a few bits of information out, but I gather that you are trying to find 2 primes that match a target. 你留下了一些信息,但我认为你试图找到2个与目标相匹配的素数。 In order to access a list in this manner, you need to enumerate it. 要以这种方式访问列表,您需要枚举它。
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
However, you don't really need the index, two for loops would accomplish the same thing. 但是,你真的不需要索引,两个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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.