2011-10-05 93 views
0

部分: (我第一個提出了字典 「H」)錯誤發生大約在Python字典功能我python腳本的

def histogram(L): 
    d= {} 
    for x in L: 
     if x in d: 
      d[x] +=1 
     else: 
      d[x] =1 
    return d 
h=histogram(LIST) 

for vhfile in vhfiles: 
    linelist=commands.getoutput('cat ' + vhfile).splitlines(True) 
    list1=[] 
    for line in linelist: 
     name1 = line.split()[0] 
     if int(h[name1]) <= 300: 
      list1.append(line) 

然後我得到了錯誤的 「如果」 行:

File "/home/xug/scratch/mrfast/NA12878/dis_rm.py", line 51, in <module> 
    if int(h[name1]) <= 300: 
KeyError: '080821_HWI-EAS301_0002_30ALBAAXX:1:46:1643:1310' 

不知道這裏發生了什麼? THX

+0

您可以更輕鬆地構建直方圖使用來自'collections'標準模塊的Counter類。 –

回答

3

你得到一個KeyError當您嘗試查找東西在dictdict不包含密鑰。

在這種情況下,看起來關鍵'080821_HWI-EAS301_0002_30ALBAAXX:1:46:1643:1310'不會發生在h

2

一個關鍵錯誤意味着你已經在你的字典中引用了一個不存在的關鍵字。在指定的密鑰處檢索值時發生錯誤,因爲該密鑰不存在。

解決此問題的一種方法是使用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})