我寫一個程式,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)
輸出:
[(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
uj5u.com熱心網友回復:
有兩種不同的方法可以對運算式進行分組。為了清楚起見,請考慮添加括號:
>>> 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'
uj5u.com熱心網友回復:
你需要重寫你的串列理解:
["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 % 3AND x % 2,然后第二個條件只檢查x % 2。
uj5u.com熱心網友回復:
對于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)]
))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/394346.html
上一篇:如何在互動式會話中重置下劃線?
下一篇:資料框特定行值選擇
