Python中字典函数出现错误

2024-04-20 10:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

python脚本的一部分: (我先编了字典“h”)

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'

知道这里发生了什么吗? 泰铢


Tags: in脚本forreturnif字典defline
2条回答

键错误意味着您在dict中引用了一个不存在的键。检索指定键处的值时出错,因为该键不存在。你知道吗

处理这个问题的一种方法是使用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>

这种倾向于异常处理而不是大量使用“if”检查的方法在Python社区中被称为“EAFP”(请求原谅比请求许可更容易)。你知道吗

在尝试引用name1之前,还可以(使用较少的Pythonic方法)检查name1是否在列表中:

if name1 in h:
    if int(h[name1]) <= 300:
       ... you get the idea

这种方法被称为“三思而后行”(LBYL)。总体而言,EAFP更可取。你知道吗

另外,你甚至不需要直方图函数。在Python2.7中,有一个Counter对象为您执行以下操作:

>>> 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})

当您试图在dict中查找某个内容时,KeyError,而dict不包含该键。你知道吗

在这种情况下,键'080821_HWI-EAS301_0002_30ALBAAXX:1:46:1643:1310'似乎不出现在h。你知道吗

相关问题 更多 >