Python 3.2 Lambda语法错误[复制]

时间:2022-07-31 22:44:43

This question already has an answer here:

这个问题已经有了答案:

def sort_dictionary( wordDict ):
    sortedList = []
    for entry in sorted(wordDict.iteritems(), key = lambda (k, v): (-v, k) ):
        sortedList.append( entry )

    return sortedList

The function would be receiving a dictionary containing information such as: { 'this': 1, 'is': 1, 'a': 1, 'large': 2, 'sentence': 1 } I would like to have it generate a list of lists, with the elements ordered first by the dictionary's values from Largest to Smallest, then by the keys alphabetically.

函数将接收一个字典,其中包含信息如:{“这”:1、“是”:1、““:1,“大”:2,“句子”:1 }我想它生成一个列表,列表的元素命令首先通过字典的值从大到小排序,然后按字母顺序的钥匙。

The function works fine when run with python 2.7.2, but I receive the error:

运行python 2.7.2时,函数运行良好,但我收到了错误:

  File "frequency.py", line 87
    for entry in sorted(wordDict.iteritems(), key = lambda (k, v): (-v, k)):
                                                           ^
SyntaxError: invalid syntax

when I run the program with python 3.2.3. I have been searching all over for a reason why, or syntax differences between 2.7 and 3.2, and have come up with nothing. Any help or fixes would be greatly appreciated.

当我使用python 3.2.3运行程序时。我一直在寻找一个原因,或者是在2.7到3.2之间的语法差异,并没有得到任何结果。非常感谢您的帮助或修复。

1 个解决方案

#1


23  

Using parentheses to unpack the arguments in a lambda is not allowed in Python3. See PEP 3113 for the reason why.

在Python3中不允许使用括号来解包参数。请参见PEP 3113。

lambda (k, v): (-v, k)

Instead use:

而不是使用:

lambda kv: (-kv[1], kv[0])

#1


23  

Using parentheses to unpack the arguments in a lambda is not allowed in Python3. See PEP 3113 for the reason why.

在Python3中不允许使用括号来解包参数。请参见PEP 3113。

lambda (k, v): (-v, k)

Instead use:

而不是使用:

lambda kv: (-kv[1], kv[0])