简体   繁体   中英

Using multiple conditional expressions within list comprehension

I am writing a program to evaluate range(1, 10) which should return divisible by 3 and even if a number is divisible by 3 and even .

If the the number is even and not divisible by 3 then it should return even .

Otherwise it should return odd .

I need to use list comprehension to evaluate multiple conditional expressions .

My program looks as below:

l = list(zip(
            range(1, 10),
            ['even and divisible by 3' if x%3 == 0 else 'even' if x%2 == 0 else 'odd' for x in range(1, 10)]
             ))

print(l)

Output:

[(1, 'odd'), (2, 'even'), (3, 'even and divisible by 3'), (4, 'even'), (5, 'odd'), (6, 'even and divisible by 3'), (7, 'odd'), (8, 'even'), (9, 'even and divisible by 3')]

I am not able to understand why program is giving (3, 'even and divisible by 3') . This is because, x%2 == 0 else 'odd' is evaluated first which should return odd

There are two different ways to group the expressions. Consider adding parentheses for clarity:

>>> x = 3
>>> 'even and divisible by 3' if x%3 == 0 else ('even' if x%2 == 0 else 'odd')
'even and divisible by 3'
>>> ('even and divisible by 3' if x%3 == 0 else 'even') if x%2 == 0 else 'odd'
'odd'

You'll need to rewrite your list comprehension:

["even and divisible by 3" if x % 3 == 0 and x % 2 == 0 else "even" if x % 2 == 0 else "odd" for x in range(1, 10)]

Note that the first conditional checks both x % 3 AND x % 2 , then the second conditional checks only x % 2 .

For x = 3 , since the first conditional is true, the expression evaluates to 'even and divisible by 3' and then stops evaluating the rest of the conditionals.

You'd only want the first conditional to be true if it was the case that the number was divisible by both 2 and 3, so you're looking for the following:

l = list(zip(
            range(1, 10),
            ['even and divisible by 3' if x%3 == 0 and x%2 == 0 else 'even' if x%2 == 0 else 'odd' for x in range(1, 10)]
             ))

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