Skip to main content
 首页 » 编程设计

python之在 Python 中的对象列表中搜索

2025年05月04日19lexus

让我们假设以下对象:

class Test: 
    id1 = "" 
    id2 = "" 
    id3 = "" 
 
    def __init__(self,arg1,arg2,arg3): 
        self.id1 = arg1 
        self.id2 = arg2 
        self.id3 = arg3 

可以看出,这个类必须包含3个唯一的id。

t = [] 
t.append(Test(200,201,193)) 
t.append(Test(403,221,213)) 
t.append(Test(3,523,2003)) 

假设上面的代码,我在列表 t 中找到 id1 = 403、id2 = 221 和 id3 =213 的对象的最简单方法是什么?

提前致谢。

请您参考如下方法:

使用带比较的迭代。

matches = [i for i in t if i.id1 == id1 and i.id2 == id2 and i.id3 == id3] 

如果你知道它在那里并且只有一个,你可以这样做:

match = next(i for i in t if i.id1 == id1 and i.id2 == id2 and i.id3 == id3) 

但是请注意,如果没有这样的项目,这将引发 StopIteration。不过,next 可以采用默认值,因此如果您不确定它是否存在,您可以指定一个默认值:

match = next((i for i in t if i.id1 == id1 and i.id2 == id2 and i.id3 == id3), None)