除条件语句外,如何从对象列表中返回符合指定条件的实例?
实现类对象列表的双条件筛选
你可以在Blah类中添加一个静态方法来封装筛选逻辑,既能复用代码,也满足你"在类中创建自定义函数"的需求。以下是具体实现:
class Blah: def __init__(self, a, b, c, d): self.a = a self.b = b self.c = c self.d = d @staticmethod def find_by_c_and_d(collection, target_c, target_d): # 遍历对象集合,返回第一个符合双条件的对象 for obj in collection: if obj.c == target_c and obj.d == target_d: return obj # 没有匹配项时返回None return None # 初始化对象和集合 obj1 = Blah("x", "t", "z", "f") obj2 = Blah("g", "w", "m", "n") objcollection = [obj1, obj2] # 调用筛选方法 matched_obj = Blah.find_by_c_and_d(objcollection, "m", "n") print(matched_obj) # 输出对应的Blah对象,可通过matched_obj.c、matched_obj.d查看属性
如果你的场景中可能存在多个符合条件的对象,可以修改方法返回所有匹配项:
@staticmethod def find_by_c_and_d(collection, target_c, target_d): matched = [] for obj in collection: if obj.c == target_c and obj.d == target_d: matched.append(obj) return matched
另外,如果你只是需要临时筛选,不用封装到类里,用列表推导式会更简洁:
# 获取所有符合条件的对象 matched_objs = [obj for obj in objcollection if obj.c == "m" and obj.d == "n"] # 只获取第一个匹配项,没有则返回None matched_obj = next((obj for obj in objcollection if obj.c == "m" and obj.d == "n"), None)
内容的提问来源于stack exchange,提问作者S S
相关产品推荐
相关产品推荐

