python一行函数定义

gut*_*rie 26 python

这必须很简单,但作为一个偶尔的python用户,与一些语法作斗争.这有效:

def perms (xs):
    for x in itertools.permutations(xs): yield list(x) 
Run Code Online (Sandbox Code Playgroud)

但这不会解析:

def perms (xs): for x in itertools.permutations(xs): yield list(x) 
Run Code Online (Sandbox Code Playgroud)

单行函数语法是否有一些限制?正文定义(for ...)可以是两行或一行,而def:可以是一行或两行,具有简单的主体,但两者结合失败.是否有排除此的语法规则?

Len*_*bro 33

是的,有限制.不,你做不到.简而言之,您可以跳过一个换行而不是两个换行.:-)

请参见http://docs.python.org/2/reference/compound_stmts.html

这样做的原因是它可以让你做到

if test1: if test2: print x
else:
    print y
Run Code Online (Sandbox Code Playgroud)

这是模棱两可的.

  • 更不用说它看起来很糟糕. (9认同)
  • 谢谢 - 正是我想要的,参考规范中的正确规则. (2认同)

Sea*_*ira 27

如果你必须有一行,只需要lambda:

perms = lambda xs: (list(x) for x in itertools.permutations(xs))
Run Code Online (Sandbox Code Playgroud)

通常情况下,当您有一个for用于生成数据的短循环时,您可以使用列表推导或生成器表达式将其替换为在相同的空间内具有大致相同的易读性.

  • pylint 会抱怨这个 - /sf/ask/1750711721/ (4认同)
  • 您还可以使用一行名为 function:`def perms(xs): return (list(x) for x in itertools.permutations(xs))` (2认同)

jer*_*rik 8

就你的情况而言,我不确定。但对于某些函数,您可以通过使用分号来实现这一点。

>>> def hey(ho): print(ho); print(ho*2); return ho*3
...
>>> hey('you ')
you
you you
'you you you '
Run Code Online (Sandbox Code Playgroud)