简体   繁体   English

if 和 else 在单行 python 循环中

[英]If and else inside a one-line python loop

Sorry if being so simple;对不起,如果这么简单; as I searched elsewhere but nobody had pointed out to this specific problem.正如我在其他地方搜索的那样,但没有人指出这个具体问题。 I'd like to learn python in a way that makes my code compact!我想以一种使我的代码紧凑的方式学习 python! So, to this end, I'm trying to make use of one-line (ie, short) loops instead of multi-line loops, specifically, for loops.因此,为此,我尝试使用单行(即短)循环而不是多行循环,特别是 for 循环。 The problem arises when I try to use one-line if and else inside the one-line loops.当我尝试在单行循环中使用单行 if 和 else 时出现问题。 It just doesn't seem to be working.它似乎不起作用。 Consider the following, for example:例如,请考虑以下情况:

numbers = ... # an arbitrary array of integer numbers

over_30 = [number if number > 30 for number in numbers]

This is problematic since one-line if does need else following it.这是因为有问题的one-line if确实需要else跟随它。 Even though, when I add else to the above script (after if ): over_30 = [number if number > 30 else continue for number in numbers] , it turns into just another pythonic error.尽管如此,当我在上面的脚本中添加else时(在if之后): over_30 = [number if number > 30 else continue for number in numbers] ,它变成了另一个pythonic错误。

I know that the problem is actually with one-line if and else, because python needs to identify a value that should be assigned to the lefthand operator.我知道问题实际上是单行 if 和 else,因为 python 需要确定一个应该分配给左手运算符的值。 But, is there a work-around for the specific use-case of this schema as above?但是,是否有针对上述模式的特定用例的解决方法?

They are different syntaxes.它们是不同的语法。 The one you are looking for is:您正在寻找的是:

over_30 = [number for number in numbers if number > 30]

This is a conditional list comprehension.这是一个条件列表理解。 The else clause is actually a non-conditional list comprehension, combined with a ternary expression: else子句实际上是一个无条件的列表推导式,结合了一个三元表达式:

over_30 = [number if number > 30 else 0 for number in numbers]

Here you are computing the ternary expression ( number if number > 30 else 0 ) for each number in the numbers iterable. (在这里,你正在计算三元表达number if number > 30 else 0 )的每个numbernumbers可迭代。

continue won't work since this is ternary expression, in which you need to return something. continue将不起作用,因为这是三元表达式,您需要返回一些内容。

val1 if condition else val2

You can try this way:你可以试试这个方法:

over_30 = [number for number in numbers if number > 30]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM