2017-02-25 97 views
2

我工作的一個項目Pygame的時候我遇到了這樣的問題:經與拉姆達的麻煩在Python

# Note: pos is the tuple that stores mouse position 
self.start_on = lambda: True if pos[1] >= 100 and pos[1] <= 200 else False 
print(self.start_on) 

回報

<function Menu.mouseLogic.<locals>.<lambda> at 0x10346d1e0> 

,而不是真或假。

我也試過:

self.start_on = (lambda: True if pos[1] >= 100 and pos[1] <= 200 else False) 
print(self.start_on) 

但返回同樣的事情。

如何讓它返回True或False?

(注:這是關於Python 3.5)

+0

不相關,但是如果你想給一個名稱分配一個lambda(一個匿名函數),只需要使用一個普通的'def'。 – skrx

回答

3

你似乎並不需要一個拉姆達。你永遠不需要寫True if X else False。你只需要

self.start_on = (100 <= pos[1] <= 200) 

如果你想使用lambda,所以你可以使用self.start_on這個條件後進行計算,這將是:

self.start_on = lambda: (100 <= pos[1] <= 200) 

,並可以打印通過它的結果print(self.start_on()),因爲你總是需要括號來調用一個函數。

2

使用lambda你不需要。只需要做self.start_on = True if pos[1] >= 100 and pos[1] <= 200 else False。甚至更簡單,self.start_on = pos[1] >= 100 and pos[1] <= 200

lambda創建一個匿名函數,但它看起來像只需要一個值。

2

你是差不多那裏。只要確保實際運行拉姆達:

self.start_on = lambda: True if pos[1] >= 100 and pos[1] <= 200 else False 
print(self.start_on()) # <-- note the() after self.start_on 

lambda調用函數後的括號。

您還可以更進一步,並簡化拉姆達:

self.start_on = lambda: (100 <= pos[1] <= 200) 
print(self.start_on())