python一行函数定义

问题描述 投票:23回答:3

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

def perms (xs):
    for x in itertools.permutations(xs): yield list(x) 

但这不会解析:

def perms (xs): for x in itertools.permutations(xs): yield list(x) 

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

python
3个回答
31
投票

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

http://docs.python.org/2/reference/compound_stmts.html

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

if test1: if test2: print x
else:
    print y

这是模棱两可的。


26
投票

如果你必须有一行,只需使它成为lambda

perms = lambda xs: (list(x) for x in itertools.permutations(xs))

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


2
投票

def perms(xs):

对于itertools.permutations(xs)中的x:yield list(x)

你可以使用exec()来解决这个问题

exec('def perms (xs):\n  for x in itertools.permutations(xs):\n   yield list(x)\n')

注意在\ n之后插入indense空格或chr(9)

如果Python在一行中的示例

for i in range(10):
 if (i==1):
  print(i)

exec('for i in range(10)\n  if (i==1):\n   print(i)\n')

This is My project on GitHub使用exec以交互式控制台模式运行Python程序

*注意多行exec仅在以'\ n'结尾时运行

© www.soinside.com 2019 - 2024. All rights reserved.