直方图:"TypeError, list indices must be integers, not str"

Histograms: "TypeError, list indices must be integers, not str"

我正在尝试制作一个函数,它将接受一个字符和一个直方图,并将该字符的一个实例添加到直方图中。到目前为止我的代码是这样的:

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

每次我尝试 运行 代码 returns 和 TypeError: list indices must be integers, not str。谁能帮我解决这个问题?我的代码实际上可能完全错误,我对此很陌生。提前致谢!

该错误是因为您试图将键分配给 list,而 list 只能由整数 list[0]list[1] 等索引.所以,hinstogram 必须是 dict 而不是 list

确保在调用 add_to_hist 方法时传递一个字典。 你可以用这种方式初始化字典:

histogram = {}

已更新

根据您的评论,您不能将 [['B',1],['a',3],['n',2],['!',1]] 作为参数传递给 add_to_his,因为那不是字典。应该是 {'B':1,'a':3,'n':2,'!':1}