简体   繁体   English

检索列表中的所有对象在python中的属性是否具有相同的值

[英]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. 您可以在all函数中使用生成器表达式。

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 ): 我想我只是一个生成器表达式(和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. 如果项目没有myAttribute属性,则具有不提高收益的潜在好处。


Note: My original answer checked that all items had the attribute "banana" with hasattr : 注意:我的原始答案检查了所有项目的hasattr属性是否为“ banana”:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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