Python中有字典解读吗? (函数返回的问题) [英] Are there dictionary comprehensions in Python? (Problem with function returning dict)

查看:125
本文介绍了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 = []
#从单词
for c in word:l.append(c)
sortedList = sorted(l)
uniqueSet = set(sortedList)
return {item:word.count(item)for unique in uniqueSet}

此代码有什么问题?为什么我得到这个 SyntaxError

  return {item:word.count(item)for unique in uniqueSet} 
^
SyntaxError:无效语法


解决方案

编辑正如agf在评论中指出的,另一个答案是Python 2.7或更新版本的字典理解。

  def countChar(word ):
return set((item,word.count(item))for set in(())

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

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

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

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


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?

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

解决方案

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

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中有字典解读吗? (函数返回的问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆