You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何接收对象属性任意组合 从对象列表中返回匹配对象

解决方案

首先你原代码中类的定义存在语法错误,def Person需要改为class Person,修正后的基础代码如下:

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

实现思路

你之前的问题是使用了or逻辑,只要满足任意一个条件就会匹配,要实现所有传入属性完全匹配,需要换成and逻辑。为了适配任意组合的属性查询、不用硬写每个属性的判断条件,可以通过关键字参数+属性反射的方式实现通用匹配。

完整实现代码

def search_persons(person_list, **query):
    # 遍历所有人员,仅保留所有查询属性都匹配的对象
    return [
        person for person in person_list
        if all(getattr(person, attr, None) == target_value for attr, target_value in query.items())
    ]

使用示例

# 搜索姓名为Matt、国籍为USA的人员,年龄不传入则不校验
matched_persons = search_persons(persons, name="Matt", country="USA")

# 输出匹配结果
for p in matched_persons:
    print(p.name, p.country, p.age)

运行后输出:

Matt USA 20

完全符合需求。

内容的提问来源于stack exchange,提问作者user10316485

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 18:36:09