在列表理解中使用多个条件表达式

Using multiple conditional expressions within list comprehension

我正在为 evaluate range(1, 10) 编写程序,如果 number is divisible by 3 and even.

应该 return divisible by 3 and even

如果数字是 even and not divisible by 3 那么它应该 return even.

否则应该return odd.

我需要使用 list comprehension 来评估多个 conditional expressions

我的程序如下所示:

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)

输出:

[(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')]

我无法理解为什么程序会给出 (3, 'even and divisible by 3')。这是因为 x%2 == 0 else 'odd' 首先被评估,应该 return odd

您需要重写您的列表理解:

["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)]

请注意,第一个条件检查 x % 3x % 2,然后第二个条件检查仅 x % 2.

有两种不同的方式来对表达式进行分组。为清楚起见,考虑添加括号:

>>> 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'

对于 x = 3,由于第一个条件为真,表达式的计算结果为 'even and divisible by 3',然后停止计算其余条件。

如果数字可以被 2 和 3 整除,您只希望第一个条件为真,因此您正在寻找以下内容:

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)]
             ))