Python While 循环单行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15185746/
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 13:34:30  来源:igfitidea点击:

While loop one-liner

pythonwhile-loop

提问by user2128561

Is it possible for to have a python while loop purely on one line, I've tried this:

是否有可能完全在一行上有一个 python while 循环,我试过这个:

while n<1000:if n%3==0 or n%5==0:rn+=n

But it produces an error message: Invalid Syntaxat the ifstatement

但它会产生一条错误消息:Invalid Syntaxif语句中

回答by Martijn Pieters

When using a compound statementin python (statements that need a suite, an indented block), and that block contains only simple statements, you can remove the newline, and separate the simple statements with semicolons.

在 python 中使用复合语句(需要套件的语句,缩进块)并且该块包含简单语句时,您可以删除换行符,并用分号分隔简单语句。

However, that does notsupport compound statements.

然而,这并不能支持复合语句。

So:

所以:

if expression: print "something"

works, but

有效,但是

while expression: if expression: print "something"

does notbecause both the whileand ifstatements are compound.

确实不是因为无论是whileif语句化合物。

For your specificexample, you can replace the if expression: assignmentpart with a conditional expression, so by using an expression instead of a complex statement:

对于您的特定示例,您可以if expression: assignment使用条件表达式替换该部分,因此使用表达式而不是复杂语句:

while expression: target = true_expression if test_expression else false_expression

in general, or while n<1000: rn += n if not (n % 3 and n % 5) else 0specifically.

一般而言,或while n<1000: rn += n if not (n % 3 and n % 5) else 0具体而言。

From a style perspective, you generally want to leave that one line on it's own, though.

不过,从风格的角度来看,您通常希望单独留下一行。

回答by l4mpi

In your example, you try to collapse two levels of blocks / indentation into a single line, which is not allowed. You can only do this with simple statements, not loops, if statements, function definitions etc. That said, for your example there is a workaround using the ternary operator:

在您的示例中,您尝试将两级块/缩进折叠为一行,这是不允许的。您只能使用简单的语句执行此操作,而不能使用循环、if 语句、函数定义等。也就是说,对于您的示例,有一种使用三元运算符的解决方法:

while n < 1000: rn += n if (n % 3 == 0 or n % 5 == 0) else 0

which reads as 'add n to rn if the condition holds, else add 0'.

如果条件成立,则读取为“将 n 添加到 rn,否则添加 0”。

回答by JHolta

It is posible to do something similar:

可以做类似的事情:

rn = 100
for n in range(10): rn += n if (n%3==0 or n%5==0) else 0