2016-12-30 65 views
-2

只有當對象的布爾屬性(數組中的對象)設置爲True時,才需要打印一些內容。目前,我想要:帶列表理解的內聯打印

print("Points of Interest: " + (" ".join([str(poi.name) for poi in currentRoom.pointsOfInterest] if [poi.found for poi in currentRoom.pointsOfInterest] else 0))) 

我在這裏失去了一些東西,因爲str(poi.name)被印刷,儘管對象的布爾屬性(poi.found)被設置爲false。

有什麼建議嗎?

在此先感謝

回答

2

[poi.found for poi in currentRoom.pointsOfInterest]創建一個列表。如果裏面有任何物體,它會變成真的。這些對象甚至可能是假的 - 只要列表不是空的,整個列表仍然會評估爲真實。您將需要使用anyall,取決於具體的行爲,你想看到的:

>>> if [0, 0]: print('y') 
... 
y 
>>> if any([0,0]): print('y') 
... 
>>> if all([0,0]): print('y') 
... 
>>> if any([]): print('y') 
... 
>>> if all([]): print('y') 
... 
y 
>>> if any([0,1]): print('y') 
... 
y 
>>> if all([0,1]): print('y') 
... 
>>> if any([1,1]): print('y') 
... 
y 
>>> if all([1,1]): print('y') 
... 
y 
+0

謝謝你,解決它! – Wretch11