2015-02-06 29 views
1

我在想如何快速查看列表中的所有對象是否都有屬性設置爲某個值,如果是這樣,運行一部分代碼。到目前爲止,在我寫的任何程序中都需要這個,我已經做了類似於下面的代碼的東西。檢索列表中的所有對象是否具有相同的python屬性值

listOfObjects = [] 
class thing(): 
    def __init__(self): 
     self.myAttribute = "banana" 
     listOfObjects.append(self) 
def checkStuff(): 
    doSomething = True 
    for i in listOfObjects: 
     if i.myAttribute != "banana": 
      doSomething = False 
    if doSomething: print("All bananas, sir!") 

我要找的是一樣的東西:

if listOfObjects.myAttribute == "banana": 
    print("All bananas, sir!") 
+1

一般你會包括後'DoSomething的= FALSE'一個'break'所以你不」不得不不必要地檢查其餘的項目。 btw'all()'在默認情況下有這種短路行爲 – jamylak 2015-02-07 03:13:56

回答

7

你可以在all功能用生成器表達式。

def checkStuff(): 
    doSomething = all(i.myAttribute == 'banana' for i in listOfObjects) 
    if doSomething: print("All bananas, sir!") 
2

我想,我只想你一個生成器表達式(和getattr):

all(getattr(item, "myAttribute", False) == "banana" for item in listOfObjects) 

這樣做,如果項目沒有一個myAttribute屬性不提高的潛在益處。


注:我原來的答覆檢查所有的項目有屬性 「香蕉」 與hasattr

all(hasattr(item, "banana") for item in listOfObjects) 
+2

這將檢查對象是否具有名爲* banana的屬性,而不是具有*值*香蕉的特定屬性。 – kindall 2015-02-06 23:56:05

+0

@ kindall更新爲使用getattr而不是hasattr。 – 2015-02-07 00:04:40

相關問題