2016-11-05 110 views
0
def countFrequency(L): 
    fdict = {} 
    for x in range(0, len(L)): 
     for key, value in fdict: 
      if L[x] == fdict[str(x)]: 
       value = value + 1 
      else: 
       fdict[L[x]] = 1 
    return fdict   

我试图计算给定字符串中特定符号出现的频率并创建一个字典。出于某种原因,该函数只是返回一个空字典。我认为问题出现在为字典添加新的值,但不知道如何解决它/修复它。添加到Python字典

input: countFrequency('MISSISSIPPI') 
output: {} 
+2

'对于key来说,fdict的值:'你的字典是空的。另外为什么你认为你需要一个for循环来添加元素到字典? – UnholySheep

+0

我正在检查该字母是否已经存在于字典中,如果是这样,我只需将其添加到字典中。 – priya

+2

如果你没有写这个作业,我强烈建议使用'collections.Counter'而不是编写你自己的代码来做同样的事情。 Python随附电池!你的整个函数体可以是'return collections.Counter(L)'。 – Blckknght

回答

0

这样做:

def countFrequency(L): 
    fdict = {} 
    for x in range(0, len(L)): 
     if str(L[x]) in fdict.keys(): 
      fdict[str(L[x])] = fdict[str(L[x])] + 1 
     else: 
      fdict[str(L[x])] = 1 
    return fdict   
0

在内环代码:

 if L[x] == fdict[str(x)]: 
      value = value + 1 
     else: 
      fdict[L[x]] = 1 

不可达,因为字典是空的initally,因此你将永远不会增加任何价值fdict

0

你可以做它喜欢这样:

def countFrequency(L): 
    fdict = {} 
    for symbol in L: #gets each letter in l 
     if symbol in fdict: #check if dhe dictionary already has an value for the symbol 
      fdict[symbol] += 1 
     else: 
      fdict[symbol] = 1 
    return fdic 
0

另一个问题是,价值value是从来没有分配到任何东西,或使用的,所以即使我们要经过循环中,我们将永远不会增加值词典。