![](/img/trans.png)
[英]IndexError: list index out of range in python, know the meaning, but don't understand why this happens
[英]IndexError: list index out of range I don't understand
該程序應該將所有可以被3和5整除的數字相加並將它們加在一起,但是我不明白,我嘗試運行此腳本,但它一直在給我錯誤:
Traceback (most recent call last):
File "first.py", line 23, in <module>
main()
File "first.py", line 19, in main
merica = merica + good[count-1]
IndexError: list index out of range
我不明白這意味着什么,因為
count-1
在似乎正確的索引范圍內?
def main():
merica = 0
commonfactors = []
good = []
count = 1
while count <= 1000:
if count%3 == 0:
good.append(count)
elif count%5 == 0:
if count in good:
commonfactors.append(count)
else:
good.append(count)
count = count+1
count = count - 1000
while count <= 1000:
merica = merica + good[count-1]
count = count+1
print(merica)
main()
exit()
任何幫助將非常感謝!
這整個塊是假設的一些長good
那是不准確的。
while count <= 1000:
merica = merica + good[count-1]
count = count+1
如果你只是把你的號碼的子集在那里,長度不能為1000。
無論如何,您應該了解內置的sum()
函數:
good = [1, 2, 3]
merica = sum(good)
您可能還會發現range()
函數也很有幫助:
for number in range(1000):
# This will loop 1000 times with number equal to 0 to 999.
這正在變成代碼審查...但是您為什么這樣做:
count = count - 1000
不僅僅是將count = 0
設置count = 0
?
您還可以從一些更具防御性的樣式編程中受益。 了解如何使用assert
:
count = count - 1000
assert count == 0
和
assert count-1 < len(good)
merica = merica + good[count-1]
這些斷言將幫助您快速跟蹤所做的假設。
祝好運!
僅當計數是3或5的倍數(不是兩個)時,才將數字追加到商品上。
因此,商品的大小不會是1000。
這就是為什么您會出錯。
您的以下循環最多只能運行<= 466。
def main():
merica = 0
commonfactors = []
good = []
count = 1
while count <= 1000:
if count%3 == 0:
good.append(count)
elif count%5 == 0:
if count in good:
commonfactors.append(count)
else:
good.append(count)
count = count+1
count = count - 1000
while count <= len(good):
merica = merica + good[count-1]
count = count+1
print(merica)
main()
exit()
由於該錯誤表明列表索引超出范圍,因此讓我們考慮列表的長度以及我們嘗試使用的索引。 在這里,假設清單good
有1000個項目,因為while循環上升到1000。
while count <= 1000:
merica = merica + good[count-1]
count = count+1
好的,現在我們看到程序期望列表中有1000個項目。 讓我們看看在構造列表時是否成立。
while count <= 1000:
if count%3 == 0:
good.append(count)
elif count%5 == 0:
if count in good:
commonfactors.append(count)
else:
good.append(count)
count = count+1
現在,我們看到列表是通過將值附加到其中(值從1到1000)而構造的。但是我們應用了一個條件來附加它,即它必須被3或5整除。那么質數呢? ? 這些數字后面沒有else
塊。 因此,我們不會附加完整的1000個數字,而只會附加可被5或3整除的數字。
解決的辦法是改變我們對第二個while塊中循環大小的假設。 while count <= len(good):
將根據列表的大小調整長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.