IndexError: Creating two lists from a text file
IndexError: Creating two lists from a text file
我不明白为什么当我 运行 我的代码时,我得到一个 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)
示例文本文件:
不满意,强烈同意
很不高兴,非常同意
高兴,同意
中立,非常同意
高兴,同意
很不高兴,非常同意
中立,非常同意
很开心,不同意
只需更改以下行,其余似乎就可以了
answers = f.read().splitlines()
我不明白为什么当我 运行 我的代码时,我得到一个 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)
示例文本文件: 不满意,强烈同意
很不高兴,非常同意
高兴,同意
中立,非常同意
高兴,同意
很不高兴,非常同意
中立,非常同意
很开心,不同意
只需更改以下行,其余似乎就可以了
answers = f.read().splitlines()