Python 3.2 Lambda 语法错误 [英] Python 3.2 Lambda Syntax Error

查看:26
本文介绍了Python 3.2 Lambda 语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

    return sortedList

该函数将接收包含以下信息的字典:{ 'this': 1, 'is': 1, 'a': 1, 'large': 2, 'sentence': 1 }我想让它生成一个列表列表,首先排列元素按字典的值从最大到最小,然后按字母顺序排列.

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.

该函数在使用 python 2.7.2 运行时工作正常,但我收到错误:

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

当我用 python 3.2.3 运行程序时.我一直在寻找原因,或者 2.7 和 3.2 之间的语法差异,但一无所获.任何帮助或修复将不胜感激.

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.

推荐答案

Python3 中不允许使用括号对 lambda 中的参数进行解包.请参阅 PEP 3113 了解原因.

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)

改为使用:

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

这篇关于Python 3.2 Lambda 语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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