這是我現在的版本的代碼,我不斷收到列表索引錯誤。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
這是我現在的版本的代碼,我不斷收到列表索引錯誤。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
您在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
謝謝你,但錯誤仍在等待中: – user3349164
主 如果list1 [n] + k == g: IndexError:列表索引超出範圍 – user3349164
我現在看到了,謝謝你哦!我認爲循環現在起作用 – user3349164
您留下了一些信息,但我收集到您正在嘗試查找與目標相匹配的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))
什麼樣的列表索引錯誤?哪裏?什麼是確切的錯誤信息? – Kevin
if list1 [n] + k == g: IndexError:列表索引超出範圍 – user3349164
它是什麼行? – Kevin