2014-11-03 26 views
0

在我的水平編輯程序,我有以下的代碼,從而消除已經移出播放區域的棋子:檢查,如果一個元組是在範圍

x, y = theobj.pos 
if x not in range(0,79): 
    level.remove_obj(theobj) 
if y not in range(0,29): 
    level.remove_obj(theobj) 

有什麼有效的辦法可以簡化這到一個單一的if語句?我已經考慮使用列表理解來生成所有有效位置元組的列表,但這似乎有點臃腫。

回答

3

你可以使用:

if not (0 <= x <= 78 and 0 <= y <= 28): 
    level.remove_obj(theobj) 

這使用chained comparisons測試對兩個邊界的兩個xy

我不會在這裏創建range()對象;您正在爲每個測試創建一個新對象。

演示:

>>> x, y = 10, 10 
>>> (0 <= x <= 78 and 0 <= y <= 28) 
True 
>>> x, y = 10, 42 
>>> (0 <= x <= 78 and 0 <= y <= 28) 
False 
>>> x, y = 81, 10 
>>> (0 <= x <= 78 and 0 <= y <= 28) 
False 
+0

這是好得多 - 雖然我還是得把它解析。 – Schilcote 2014-11-03 14:50:11

+0

@Schilcote:你仍然需要解壓縮或內聯。 '如果不是(0 <= theobj.pos [0] <= 78且0 <= theobj.pos [1] <= 28):'不是太糟糕。 – 2014-11-03 14:50:52

+0

或使用lambda – 2014-11-03 14:58:29

相關問題