一個關鍵錯誤意味着你已經在你的字典中引用了一個不存在的關鍵字。在指定的密鑰處檢索值時發生錯誤,因爲該密鑰不存在。
解決此問題的一種方法是使用try/except塊。如果'try'中的代碼引發'KeyError',那麼您知道name1不在h中,並且您可以執行任何適當的操作。
for line in linelist:
name1 = line.split()[0]
try:
if int(h[name1]) <= 300:
list1.append(line)
except KeyError:
<code here to deal with the condition>
猖獗的使用有利於異常處理的這種方法「如果」檢查Python社區爲「EAFP」是已知的(更容易請求原諒比許可)。
你也可以(使用更少的Python的方式)檢查名1是在列表中嘗試引用之前:
if name1 in h:
if int(h[name1]) <= 300:
... you get the idea
這種方法被稱爲「三思而後行」(LBYL)。總的來說,EAFP總體上是優選的。
另外,你甚至不需要直方圖功能。在Python 2.7,有一個計數器對象,這是否對你:
>>> LIST = "This is a sentence that will get split into multiple list elements. The list elements will get counted using defaultdict, so you don't need the histogram function at all.".split()
>>> LIST
['This', 'is', 'a', 'sentence', 'that', 'will', 'get', 'split', 'into', 'multiple', 'list', 'elements.', 'The', 'list', 'elements', 'will', 'get', 'counted', 'using', 'defaultdict,', 'so', 'you', "don't", 'need', 'the', 'histogram', 'function', 'at', 'all.']
>>> from collections import Counter
>>> c = Counter(LIST)
>>> c
Counter({'get': 2, 'list': 2, 'will': 2, 'defaultdict,': 1, 'elements.': 1, "don't": 1, 'is': 1, 'at': 1, 'need': 1, 'sentence': 1, 'split': 1, 'you': 1, 'into': 1, 'function': 1, 'elements': 1, 'multiple': 1, 'that': 1, 'This': 1, 'histogram': 1, 'using': 1, 'The': 1, 'a': 1, 'all.': 1, 'so': 1, 'the': 1, 'counted': 1})
預2.7,你可以使用defaultdict得到相同的結果:
>>> from collections import defaultdict
>>> dd = defaultdict(int)
>>> for word in LIST:
... dd[word] += 1
...
>>> dd
defaultdict(<type 'int'>, {'defaultdict,': 1, 'elements.': 1, "don't": 1, 'is': 1, 'at': 1, 'need': 1, 'sentence': 1, 'split': 1, 'get': 2, 'you': 1, 'into': 1, 'function': 1, 'elements': 1, 'multiple': 1, 'that': 1, 'This': 1, 'histogram': 1, 'using': 1, 'The': 1, 'a': 1, 'all.': 1, 'list': 2, 'will': 2, 'so': 1, 'the': 1, 'counted': 1})
您可以更輕鬆地構建直方圖使用來自'collections'標準模塊的Counter類。 –