python一行函数定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16756174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:34:42  来源:igfitidea点击:

python one line function definition

python

提问by guthrie

This must be simple, but as an only occasional python user, fighting some syntax. This works:

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

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

But this won't parse:

但这不会解析:

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

Is there some restriction on the one-line function syntax? The body definition (for...) can be either two or one line by itself, and the def: can be one or two lines with a simple body, but combining the two fails. Is there a syntax rule that excludes this?

对单行函数语法有什么限制吗?主体定义 (for...) 本身可以是两行或一行,而 def: 可以是一两行并带有一个简单的主体,但将两者结合起来会失败。是否有排除此的语法规则?

采纳答案by Lennart Regebro

Yes, there are restrictions. No, you can't do that. Simply put, you can skip one line feed but not two. :-)

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

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

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

The reason for this is that it would allow you to do

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

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

Which is ambiguous.

这是模棱两可的。

回答by Sean Vieira

If you musthave one line just make it a lambda:

如果您必须有一行,只需将其设为lambda

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

Quite often, when you have a short forloop for generating data you can replace it with either list comprehension or a generator expression for approximately the same legibility in slightly less space.

很多时候,当你有一个for用于生成数据的短循环时,你可以用列表理解或生成器表达式替换它,以在稍微更少的空间内获得大致相同的易读性。

回答by Supot Sawangpiriyakij

def perms (xs):

定义烫发(xs):

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

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

You can use exec()to help this problem

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

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

beware to insert indented spacing or chr(9) after \n

注意在 \n 之后插入缩进的间距或 chr(9)

Example for if Python in one line

如果 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 GitHubto use exec to run Python program in interactive console mode

这是我在 GitHub上使用 exec 在交互式控制台模式下运行 Python 程序的项目

*note multiple line exec run only when end with '\n'

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