【问题标题】:Are there dictionary comprehensions in Python? (Problem with function returning dict)Python中有字典理解吗? (函数返回dict的问题)
【发布时间】: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


【解决方案1】:

如果您使用的是 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

【讨论】:

  • Python 的语法总是让我觉得我在作弊。为什么其他语言没有这么简单?
【解决方案2】:

edit:正如 agf 在 cmets 和其他答案中指出的那样,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() 内置函数。

【讨论】:

  • 你的代码,太短了,可以用,不过我是初学者,有其他初学者的方法吗。
  • @newbie - 我将它从 lambda 转换为普通函数定义,我将添加一些额外的解释。
  • Python 2.7 及更新版本字典理解。
  • @agf - 谢谢,我没有意识到这一点。我编辑了我的答案并为你的答案投票!
  • @AndrewClark 您的代码没有演示字典理解,它演示了使用 2.7 之前的 Python 版本的解决方法(例如,这对我们这些运行 Jython 2.5.3 的人很有用)
猜你喜欢
  • 1970-01-01
  • 2023-03-28
  • 2013-11-30
  • 2017-05-07
  • 1970-01-01
  • 2018-05-15
  • 2015-06-23
  • 2019-10-14
相关资源
最近更新 更多