[英]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
每次我嘗試運行代碼時它返回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}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.