Python中有字典理解吗?(函数返回dict的问题)

new*_*bie 25 python dictionary python-2.x

我知道列表理解,字典理解怎么样?

预期产出:

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

代码(我是初学者):

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 }
Run Code Online (Sandbox Code Playgroud)

这段代码有什么问题?为什么我这样做SyntaxError

return { item:word.count(item) for item in uniqueSet }
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

agf*_*agf 66

如果您使用的是Python 2.7或更高版本:

{item: word.count(item) for item in set(word)}
Run Code Online (Sandbox Code Playgroud)

工作良好.在设置列表之前,无需对列表进行排序.您也不需要将单词转换为列表.此外,您正在使用足够新的Python来collections.Counter(word)代替.

如果您使用的是旧版本的Python,则无法使用dict理解,您需要使用dict构造函数的生成器表达式:

dict((item, word.count(item)) for item in set(word))
Run Code Online (Sandbox Code Playgroud)

这仍然需要你迭代word len(set(word))一次,所以尝试类似:

from collections import defaultdict
def Counter(iterable):
    frequencies = defaultdict(int)
    for item in iterable:
        frequencies[item] += 1
    return frequencies
Run Code Online (Sandbox Code Playgroud)

  • Python的语法总是让我觉得我在欺骗.为什么其他语言不那么简单? (7认同)

And*_*ark 32

编辑:正如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}
Run Code Online (Sandbox Code Playgroud)

word由于字符串是可迭代的,因此无需转换为列表或对其进行排序,然后将其转换为集合:

>>> set('google')
set(['e', 'o', 'g', 'l'])
Run Code Online (Sandbox Code Playgroud)

对于Python 2.6及更低版本,没有字典理解,这可能是您看到语法错误的原因.另一种方法是使用理解或生成器创建键值元组列表,并将其传递给dict()内置函数.

  • 有___is___对Python 2.7和更新版本的字典理解. (4认同)