如何从 Python 中的对象列表中接收对象属性和 return 匹配对象的任意组合?

How to receive any combination of an object's attributes and return the matching objects from a list of objects in Python?

很抱歉,如果之前有人回答过这个问题,但我根本找不到这个问题的任何答案。

假设我有这个 class 和对象列表:

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)]

现在我希望用户通过输入属性值的任意组合来搜索一个人,并且我希望 return 专门具有所有这些值的对象。例如,如果用户输入:'Matt'、'USA' 并且没有年龄,我希望程序 return 只有第三人称 Matt 来自美国,而不是 return 所有三个对象,因为它们都有一些输入的属性值组合。

我的实现目前使用带有 or 运算符的 if 语句,如果一个语句为真,它将 return 所有对象,因为使用 or 将 return 所有对象,这就是我正在尝试解决。

提前致谢。

您可以对任务使用列表理解。并且 if 条件应该检查​​值是否为 None 否则检查列表。

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]]