簡體   English   中英

檢索列表中的所有對象在python中的屬性是否具有相同的值

[英]Retrieving if all objects in a list have the same value for an attribute in 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!")

您可以在all函數中使用生成器表達式。

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

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

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

如果項目沒有myAttribute屬性,則具有不提高收益的潛在好處。


注意:我的原始答案檢查了所有項目的hasattr屬性是否為“ banana”:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM