Python里有字典的理解吗?(功能返回指令的问题)

时间:2022-01-27 01:04:17

I know about list comprehensions, what about dictionary comprehensions?

我知道关于列表的理解,字典的理解是什么?

Expected Output:

预期的输出:

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

Code (I'm a beginner):

代码(我是一个初学者):

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 }

What is the problem with this code? Why do I get this SyntaxError?

这段代码有什么问题?为什么会有SyntaxError?

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

2 个解决方案

#1


29  

edit: As agf pointed out in comments and the other answer, there is a dictionary comprehension for Python 2.7 or newer.

编辑:正如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}

There is no need to convert word to a list or sort it before turning it into a set since strings are iterable:

不需要将单词转换为列表或将其排序,然后将其转换为一个集合,因为字符串是可迭代的:

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

There is no dictionary comprehension with for Python 2.6 and below, which could be why you are seeing the syntax error. The alternative is to create a list of key-value tuples using a comprehension or generator and passing that into the dict() built-in.

对于Python 2.6和以下,没有字典理解,这可能是您看到语法错误的原因。另一种方法是使用理解或生成器创建键值元组列表,并将其传递到内置的命令()。

#2


60  

If you're on Python 2.7 or newer:

如果你使用的是Python 2.7或更新版本:

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

works fine. You don't need to sort the list before you set it. You also don't need to turn the word into a list. Also, you're on a new enough Python to use collections.Counter(word) instead.

工作很好。在设置列表之前,不需要对列表进行排序。你也不需要把这个词变成一个列表。另外,您还可以使用一个新的Python来使用collections.Counter(word)。

If you're on an older version of Python, you can't use dict comprehensions, you need to use a generator expression with the dict constructor:

如果您使用的是较老版本的Python,您不能使用命令理解,您需要使用命令构造函数来使用生成器表达式:

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

This still requires you to iterate over word len(set(word)) times, so try something like:

这仍然需要您遍历单词len(set(word)),所以尝试如下方法:

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

#1


29  

edit: As agf pointed out in comments and the other answer, there is a dictionary comprehension for Python 2.7 or newer.

编辑:正如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}

There is no need to convert word to a list or sort it before turning it into a set since strings are iterable:

不需要将单词转换为列表或将其排序,然后将其转换为一个集合,因为字符串是可迭代的:

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

There is no dictionary comprehension with for Python 2.6 and below, which could be why you are seeing the syntax error. The alternative is to create a list of key-value tuples using a comprehension or generator and passing that into the dict() built-in.

对于Python 2.6和以下,没有字典理解,这可能是您看到语法错误的原因。另一种方法是使用理解或生成器创建键值元组列表,并将其传递到内置的命令()。

#2


60  

If you're on Python 2.7 or newer:

如果你使用的是Python 2.7或更新版本:

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

works fine. You don't need to sort the list before you set it. You also don't need to turn the word into a list. Also, you're on a new enough Python to use collections.Counter(word) instead.

工作很好。在设置列表之前,不需要对列表进行排序。你也不需要把这个词变成一个列表。另外,您还可以使用一个新的Python来使用collections.Counter(word)。

If you're on an older version of Python, you can't use dict comprehensions, you need to use a generator expression with the dict constructor:

如果您使用的是较老版本的Python,您不能使用命令理解,您需要使用命令构造函数来使用生成器表达式:

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

This still requires you to iterate over word len(set(word)) times, so try something like:

这仍然需要您遍历单词len(set(word)),所以尝试如下方法:

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