Python 3.2 Lambda Syntax Error [duplicate]

萝らか妹 提交于 2019-11-27 01:19:39

问题


This question already has an answer here:

  • Nested arguments not compiling 1 answer
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.

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

  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.


回答1:


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

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

Instead use:

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


来源:https://stackoverflow.com/questions/15712210/python-3-2-lambda-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!