这是我得到的错误 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秒到达战场
TA贡献1828条经验 获得超6个赞
它与您访问数组的方式有关。有一个更好的方法:
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")
添加回答
举报
0/150
提交
取消