Why doesn't Python allow to put a for followed by an if on the same line?

为什么不Python允许将紧随其后的是一种如果在同一行?

Tags: python
标签: python

问题 (Question)

Why is this code

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

valid while the compound statement (I know that PEP 8 discourage such coding style)

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

is not?

为什么这段代码

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

有效而复合语句(我知道PEP 8阻碍这种编码风格)

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

不是吗?

最佳答案 (Best Answer)

This is because python has strict rules about indentation being used to represent blocks of code and by putting an for followed by an if, you create ambiguous indentation interpretations and thus python does not allow it.

For python, you can put as many lines as you want after a if statement:

if 1==1: print 'Y'; print 'E'; print 'S'; print '!';

as long as they all have the same indentation level, i.e., no if, while, for as they introduce a deeper indentation level.

Hope that helps

这是因为python有严格的规则缩进被用来表示代码块和将一个for紧随其后的是一个if,您将创建python模棱两可的缩进的解释,因此不允许它。

在python中,你可以把你想要尽可能多的行后if声明:

if 1==1: print 'Y'; print 'E'; print 'S'; print '!';

只要他们都有相同的缩进级别,即。,没有if ,while ,for他们引入一个更深的缩进级别。

希望这有助于

答案 (Answer) 2

using list comprehension:

In [10]: [x for x in range(10) if x ==5][0]
Out[10]: 5

使用列表理解:

In [10]: [x for x in range(10) if x ==5][0]
Out[10]: 5

答案 (Answer) 3

The reason why you cannot is because the language simply doesn't support it:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

It has been suggested many times on the Python mailing lists, but has never really gained traction because it's already possible to do using existing mechanisms...

Such as a filtered generator expression:

for i in (i for i in range(10) if i == 5):
    ...

The advantage of this over the list comprehension is that it doesn't generate the entire list before iterating over it.

你不能因为的原因语言不支持它:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

它已经被提出很多次在Python邮件列表,但从未真正获得牵引力,因为它已经可以使用现有的机制…

如过滤生成器表达式:

for i in (i for i in range(10) if i == 5):
    ...

这在列表理解的优点是,它不产生在遍历整个列表。

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/23451310