2016-11-19 67 views
0

在我的作業中,這個問題是要求我創建一個函數,在這個函數中,Python應該創建字典,以長字符串中的某個字母開頭的字數是對稱的。對稱意味着該單詞以一個字母開頭,並以同一個字母結尾。我不需要此算法的幫助。我絕對知道我的確是對的,但是我只需要解決這個我無法弄清楚的關鍵錯誤。我寫了d[word[0]] += 1,它是以該特定字母開始的單詞的頻率加1。字典中的重要錯誤。如何讓Python打印我的字典?

輸出應該是這樣的(使用我在下面提供的字符串): {'d': 1, 'i': 3, 't': 1}

t = '''The sun did not shine 
it was too wet to play 
so we sat in the house 
all that cold cold wet day 

I sat there with Sally 
we sat there we two 
and I said how I wish 
we had something to do''' 

def symmetry(text): 
    from collections import defaultdict 
    d = {} 
    wordList = text.split() 
    for word in wordList: 
     if word[0] == word[-1]: 
      d[word[0]] += 1 
    print(d) 
print(symmetry(t)) 

回答

1

你試圖增加至今尚未作出導致KeyError一個項的值。當還沒有關鍵項時,您可以使用get();將作出默認0或您選擇的任何其他值)。用這種方法,你不需要defaultdict,儘管在某些情況下非常有用)。

def symmetry(text): 
    d = {} 
    wordList = text.split() 
    for word in wordList: 
     key = word[0] 
     if key == word[-1]: 
      d[key] = d.get(key, 0) + 1 
    print(d) 
print(symmetry(t)) 

樣本輸出

{'I': 3, 'd': 1, 't': 1} 
+1

謝謝!這是做到這一點的正確方法!有效!希望我將來不會通過使用你的代碼(我從你那裏得到的改正部分)得到關鍵錯誤, – Jorgan

1

你從來沒有真正使用collections.defaultdict,雖然你導入。初始化ddefaultdict(int),而不是{},你很好去。

def symmetry(text): 
    from collections import defaultdict 
    d = defaultdict(int) 
    wordList = text.split() 
    for word in wordList: 
     if word[0] == word[-1]: 
      d[word[0]] += 1 
    print(d) 

print(symmetry(t)) 

結果:

defaultdict(<class 'int'>, {'I': 3, 't': 1, 'd': 1})