简体   繁体   中英

Retrieving if all objects in a list have the same value for an attribute in python

I'm wondering how to quickly see if all objects in a list have an attribute set to a certain value, and if so run a portion of code. So far, in any program that I've written that needs this, I've done something similar to the code below.

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!")

What I'm looking for is something like:

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

You could use a generator expression in the all function.

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

I think I would just you a generator expression (and getattr ):

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

This has the potential benefit of not raising if item doesn't have a myAttribute attribute.


Note: My original answer checked that all items had the attribute "banana" with hasattr :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM