簡體   English   中英

在列表理解中使用多個條件表達式

[英]Using multiple conditional expressions within list comprehension

我正在編寫一個程序來evaluate range(1, 10) ,它應該返回divisible by 3 and even一個number is divisible by 3 and even

如果數字是even and not divisible by 3那么它應該返回even

否則它應該返回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)

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

我無法理解程序為什么給出(3, 'even and divisible by 3') 這是因為, x%2 == 0 else 'odd'首先被評估應該返回odd

有兩種不同的方式來對表達式進行分組。 為了清楚起見,考慮添加括號:

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

你需要重寫你的列表理解:

["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' ,然后停止計算條件的 rest。

如果數字可以被 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)]
             ))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM