【问题标题】:IndexError: Creating two lists from a text fileIndexError:从文本文件创建两个列表
【发布时间】: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
  • 每个条目之间有一个空的新行?

标签: python list histogram


【解决方案1】:

只需更改以下行,其余的似乎都可以

answers = f.read().splitlines()

【讨论】:

  • 当我这样做时,它说 AttributeError: module ‘matplotlib.pyplot’ has no attribute ‘bars’
  • pyplot 中没有bars 方法。应该是bar。将代码更改为plt.bar
  • 我发现这个错误在说什么!我不小心输入了“plt.bars(.....)”而不是 plt.bar。非常感谢你的帮助!我喜欢个人资料图片顺便说一句。我最喜欢的动漫之一
猜你喜欢
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-22
  • 1970-01-01
相关资源
最近更新 更多