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

查看:64
本文介绍了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,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天全站免登陆