简体   繁体   English

直方图:“TypeError,列表索引必须是整数,而不是str”

[英]Histograms: “TypeError, list indices must be integers, not str”

I am trying to make a function that will take a character and a histogram and add an instance of that character to the histogram. 我正在尝试创建一个将采用字符和直方图的函数,并将该字符的实例添加到直方图中。 My code so far is like this: 到目前为止我的代码是这样的:

def add_to_hist(character, histogram):
    """Takes a character and a histogram and adds an occurrence
       of that character to the histogram.

    string, list -> list"""
    for c in character:
        if c not in histogram:
            histogram[c] = 1
        else:
            histogram[c] = histogram[c]+1
    return histogram

Every time I try to run the code it returns with TypeError: list indices must be integers, not str . 每次我尝试运行代码时它返回TypeError: list indices must be integers, not str Can anyone help me figure this out? 任何人都可以帮我解决这个问题吗? My code actually might be entirely wrong, I'm very new at this. 我的代码实际上可能完全错了,我对此非常陌生。 Thanks in advance! 提前致谢!

That error is because you are trying to assign a key to a list , and list only can be indexed by intenger list[0] , list[1] , so on. 该错误是因为您尝试将键分配给list ,而list只能由整数list[0]list[1]索引。 So, hinstogram must be a dict not a list 因此, hinstogram必须是dict而不是list

Make sure when you call add_to_hist method, pass a dict. 确保在调用add_to_hist方法时,传递一个字典。 You can init a dict in that way: 你可以用这种方式初始化一个字典:

histogram = {}

UPDATED 更新

Based on your comment, you can't pass [['B',1],['a',3],['n',2],['!',1]] as param to add_to_his , because that is not a dict. 根据你的评论,你不能将[['B',1],['a',3],['n',2],['!',1]]作为参数传递给add_to_his ,因为不是一个字典。 It should be {'B':1,'a':3,'n':2,'!':1} 它应该是{'B':1,'a':3,'n':2,'!':1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM