![](/img/trans.png)
[英]Returning all objects in list which have the same attribute as another object?
[英]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!")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.