简体   繁体   中英

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! So, to this end, I'm trying to make use of one-line (ie, short) loops instead of multi-line loops, specifically, for loops. The problem arises when I try to use one-line if and else inside the one-line loops. 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. 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.

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. 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:

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.

continue won't work since this is ternary expression, in which you need to return something.

val1 if condition else val2

You can try this way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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