简体   繁体   中英

Group objects if multiple attributes are same in python

def class ObjClass:
    attr1;
    attr2;
    attr3;
    attr4;
    attr5;

    def __init__(self):
       print("Some logic goes here")

In another .py file

obj1 = obj.objClass();
obj1.attr1 = foo
obj1.attr2 = bar   (..... so on and so forth)

objList = []
objList.append(obj1)
objList.append(obj2)
objList.append(obj3)
objList.append(obj4)
objList.append(obj5)

Now all the objects that are there in this list, I want to group the ones that have the same attr1, attr2, attr3 but different attr4 and attr5. How do I do this?

What is the pythonic way of doing this. I know how to do this using lists but not using objects.

def grouper(objs, attr_name):
    group =[]
    for obj in objs:
        if hasattr(obj, attr_name):
            group.append(obj)
    return group

Returns a list of objects- with the attribute you select equal to the value you want.

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