【发布时间】:2021-11-19 03:54:48
【问题描述】:
我不明白为什么当我运行我的代码时我得到一个 IndexError 说我的列表超出范围。我在“ if x[1] == "strongly agree": "处遇到错误。我已经多次检查我的代码,但我不知道如何修复..
这是我的代码(不包括导入):
firstList = [0, 0, 0, 0, 0]
secondList = [0, 0, 0, 0, 0]
with open("surveyData.txt", 'r') as f:
answers = f.read().split('\n')
for x in answers:
x = x.split(',')
if x[0] == "very happy":
firstList[0] += 1
elif x[0] == "happy":
firstList[1] += 1
elif x[0] == "neutral":
firstList[2] += 1
elif x[0] == "unhappy":
firstList[3] += 1
else:
firstList[4] += 1
if x[1] == "strongly agree":
secondList[0] += 1
elif x[1] == "agree":
secondList[1] += 1
elif x[1] == "neutral":
secondList[2] += 1
elif x[1] == "disagree":
secondList[3] += 1
else:
secondList[4] += 1
def showHistogram(dataList, bars):
plt.bars(bars, dataList)
plt.show()
question1_freq = ['very happy', ' happy', 'neutral', 'unhappy', 'very unhappy']
showHistogram(firstList, question1_freq)
question2_freq = ['strongly agree', 'agree', 'neutral', 'disagree', 'strongly disagree']
showHistogram(secondList, question2_freq)
示例文本文件: 不满意,强烈同意
非常不满意,非常同意
高兴,同意
中立,非常同意
高兴,同意
非常不满意,非常同意
中立,非常同意
很高兴,不同意
【问题讨论】:
-
能不能也加个surveyData.txt的样例
-
@LeelaPrasad 好的,我会编辑它
-
每对调查数据条目是用换行还是空格分隔?
-
换行@LeelaPrasad
-
每个条目之间有一个空的新行?