Python if语句“SyntaxError:无效语法”

2024-10-01 15:49:25 发布

您现在位置:Python中文网/ 问答频道 /正文

试图执行某人的代码,得到语法错误。不知道为什么:(

def GetParsers( self, systags ):
    childparsers = reduce( lambda a,b : a+b, [[]] + [ plugin.GetParsers( systags ) for plugin in self.plugins ] )
    parsers = [ p for plist in [ self.parsers[t] for t in systags if self.parsers.has_key(t) ] for p in plist ]
    return reduce( lambda a,b : ( a+[b] if not b in a else a ), [[]] + parsers + childparsers )

错误是

^{pr2}$

Python版本

Python 2.2.3 (#1, May  1 2006, 12:33:49)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-54)] on linux2

                                         ^                                             

Tags: lambda代码inselfreduceforifdef
3条回答

您需要将Python安装升级到至少2.5版本。More Information

条件表达式是在2.5(source)中添加的-您有2.2。所以我担心你没有条件表达。他们只是在那个版本中还不存在。如果可以的话,绝对更新(不仅仅是为了这个小小的改变,从06年开始已经有上千个了)。在

升级到Python的更新版本将是最好的解决方案,但是如果由于某种原因无法升级,可以更新代码以使用the and-or trick。在

所以这个:

>>> 'a' if 1 == 2 else 'b'
'b'

变成:

^{pr2}$

这里有一个小问题,如果为True返回的值本身的计算结果为False,则该语句将无法按您的要求工作。您可以按照以下方法解决此问题:

>>> ((1 == 2) and ['a'] or ['b'])[0]
'b'

在这种情况下,因为值是一个非空列表,它永远不会计算为False,所以技巧始终有效。在

相关问题 更多 >

    热门问题