Home > Net >  How to receive any combination of an object's attributes and return the matching objects from a
How to receive any combination of an object's attributes and return the matching objects from a

Time:11-27

I am sorry if this was answered before, but I could not find any answer for this problem at all.

Let's say I have this class and list of objects:

def Person:
    def __init__(self, name, country, age):
        self.name = name
        self.country = country
        self.age = age
persons = [Person('Tom', 'USA', 20), Person('Matt', 'UK', 19), Person('Matt', 'USA', 20)]

Now I would like the user to search for a person by entering any combination of attribute values and I want to return the objects that have all these values exclusively. For example, if the user enters: 'Matt', 'USA' and no age, I want the program to return the third person only who's Matt and is from the USA and not return all three objects because all of them have some of the entered combination of attribute values.

My implementation currently uses an if statement with the or operator which would return all the objects since the usage of or would return all the objects if one statement is True, which is what I am trying to solve.

Thanks in advance.

CodePudding user response:

You can use a list comprehension for the task. And the if condition should check if the value is None else check in the list.

class Person:
    def __init__(self, name, country, age):
        self.name = name
        self.country = country
        self.age = age
    def __repr__(self):
        return "[{},{},{}]".format(name, country, str(age))
persons = [Person('Tom', 'USA', 20), Person('Matt', 'UK', 19), Person('Matt', 'USA', 20)]
name = "Matt"
country = "USA"
age = None
result = [
    p for p in persons
    if (name == None or p.name == name) and 
    (country == None or p.country == country) and 
    (age == None or p.age == age)
]
print(result) #[[Matt,USA,None]]
  • Related