2011-09-01 77 views
21

我知道列表推導,那麼字典解析呢?Python中是否有字典解析? (函數返回字典的問題)

預期輸出:

>>> countChar('google') 
    {'e': 1, 'g': 2, 'l': 1, 'o': 2} 
    >>> countLetters('apple') 
    {'a': 1, 'e': 1, 'l': 1, 'p': 2} 
    >>> countLetters('') 
    {} 

代碼(我是初學者):

def countChar(word): 
    l = [] 
    #get a list from word 
    for c in word: l.append(c) 
    sortedList = sorted(l) 
    uniqueSet = set(sortedList) 
    return {item:word.count(item) for item in uniqueSet } 

如何處理此代碼的問題是什麼?爲什麼我得到這個SyntaxError

return { item:word.count(item) for item in uniqueSet } 
^ 
SyntaxError: invalid syntax 
+1

的語法錯誤是多餘')':'word.count(項))' –

+1

corrected.but問題仍然得不到解決 – newbie

+0

能ÿ你粘貼實際的錯誤,你會得到什麼? – SingleNegationElimination

回答

29

編輯:作爲AGF的意見和對方的回答中指出,還有就是Python 2.7或更高版本的字典理解。

def countChar(word): 
    return dict((item, word.count(item)) for item in set(word)) 

>>> countChar('google') 
{'e': 1, 'g': 2, 'o': 2, 'l': 1} 
>>> countChar('apple') 
{'a': 1, 'p': 2, 'e': 1, 'l': 1} 

沒有必要word轉換到一個列表或者把它變成一個集之前對其進行排序,因爲字符串是可迭代:

>>> set('google') 
set(['e', 'o', 'g', 'l']) 

沒有字典的理解與適用於Python 2.6及以下,這可能是你看到語法錯誤的原因。另一種方法是使用理解或生成器創建鍵值元組列表,並將其傳遞到dict()內置的列表中。

+0

您的代碼,它太短,它的工作原理,但我是一個初學者,有其他方式爲初學者。 – newbie

+1

@newbie - 我將它從一個'lambda'切換到一個正常的函數定義,我將添加一些額外的解釋。 –

+0

謝謝你的解釋。 – newbie

60

如果你在Python 2.7版或更新版本:

{item: word.count(item) for item in set(word)} 

工作正常。在設置之前,您不需要對列表進行排序。你也不需要把這個詞變成一個列表。另外,您已經使用了足夠新的Python來代替collections.Counter(word)

如果您使用的是舊版本的Python,您不能使用dict解析,你需要使用發電機的表達與dict構造:

dict((item, word.count(item)) for item in set(word)) 

這仍然需要你在word迭代len(set(word))倍,所以你可以試試:

from collections import defaultdict 
def Counter(iterable): 
    frequencies = defaultdict(int) 
    for item in iterable: 
     frequencies[item] += 1 
    return frequencies 
+5

Python的語法總是讓我感覺自己像是'米作弊。爲什麼其他語言不這麼簡單? – ArtOfWarfare