我知道列表推導,那麼字典解析呢?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
的語法錯誤是多餘')':'word.count(項))' –
corrected.but問題仍然得不到解決 – newbie
能ÿ你粘貼實際的錯誤,你會得到什麼? – SingleNegationElimination