【发布时间】:2011-09-01 21:03:40
【问题描述】:
我知道列表推导,字典推导呢?
预期输出:
>>> 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(item)) -
已更正。但仍有问题
-
你能粘贴你得到的实际错误吗?
-
from collections import Counter as countChar
标签: python dictionary python-2.x