Python 3.2 Lambda 语法错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15712210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:45:17  来源:igfitidea点击:

Python 3.2 Lambda Syntax Error

pythonlambdasyntax-error

提问by Zack

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.

该函数将接收包含以下信息的字典:{ 'this': 1, 'is': 1, 'a': 1, 'large': 2, 'sentence': 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 之间的语法差异,但一无所获。任何帮助或修复将不胜感激。

采纳答案by unutbu

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

Python3 中不允许使用括号来解压 lambda 中的参数。原因参见PEP 3113

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

Instead use:

而是使用:

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