這是我得到的錯誤 word[i] += len(words) IndexError: list index out of range這是代碼word=[]i=1with open("poem.txt", "r") as f: for line in f: words=line.split() word[i] += len(words) i += 1for i in range(1,20): print("For the line "+i+" we have "+word[i]+" words")我想要作為輸出的東西是這樣的對于第 1 行,我們有 10 個單詞對于第 2 行,我們有 20 個單詞等等 ...
2 回答

30秒到達(dá)戰(zhàn)場
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個贊
它與您訪問數(shù)組的方式有關(guān)。有一個更好的方法:
word=[]
with open("poem.txt", "r") as f:
for line in f:
words=line.split()
word.append(len(words))
for idx, count in enumerate(word):
print("For the line " + (idx + 1) + " we have " + count + " words")

冉冉說
TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個贊
第一次代碼運(yùn)行字將有 0 個元素,但 i 是 1,因此位置 1 處沒有項(xiàng)目。
嘗試從 i=0 開始
word=[] i=0
添加回答
舉報
0/150
提交
取消