Skip to main content
 首页 » 编程设计

Python之返回一个唯一的对象列表

2024年10月24日7yjmyzz

我正在尝试获取一个唯一的对象列表,我有一些代码可以从 API 中提取数据,然后将该数据放入一个对象中。然后我将这些对象放在一个列表中。但是有些对象是重复的,我想知道如何删除它们?

示例列表数据:

[ 
Policy: 'SQL',  
SecondaryPolicy: 'ORACLE',  
Level: 'Primary On Call Engineer', 
LevelNo: 1,  
StartDate: None,  
EndDate: None,  
StartTime: None,  
EndTime: None,  
Name: 'Fred',  
Mobile: '123',  
 
Policy: 'Comms',  
SecondaryPolicy: '',  
Level: 'Primary On Call Engineer', 
LevelNo: 1,  
StartDate: None,  
EndDate: None,  
StartTime: None,  
EndTime: None,  
Name: 'Bob',  
Mobile: '456',  
 
Policy: 'Infra',  
SecondaryPolicy: '',  
Level: 'Primary On Call Engineer', 
LevelNo: 1,  
StartDate: None,  
EndDate: None,  
StartTime: None,  
EndTime: None,  
Name: 'Bill',  
Mobile: '789',  
 
Policy: 'Comms',  
SecondaryPolicy: '',  
Level: 'Primary On Call Engineer', 
LevelNo: 1,  
StartDate: None,  
EndDate: None,  
StartTime: None,  
EndTime: None,  
Name: 'Bob',  
Mobile: '456',  
] 

代码(我删除了一些对象数据并放入了样本数据,对于这个测试我只是试图让 freds 结果返回一次)

objPolicyData = getUserData() 
 
OnCallData = []  
for UserItem in objPolicyData['users']:    
    UserData = User()      
    #get the user object from DB 
    UserData.Name   = 'Fred' 
    for OnCall in UserItem['on_call']:     
        UserPolicy = OnCall['escalation_policy']  
        UserData.Policy          = 'SQL' 
        UserData.SecondaryPolicy = 'ORACLE' 
        OnCallData.append(UserData) 

尝试: 我试过了

clean_on_call_data = {User.Name for User in OnCallData} 

但这只会打印

set(['Fred']) 

对象中的其他字段在哪里,我将如何迭代它?

编辑:这是我的课,cmp 正确吗?我如何删除重复项?

class User(object): 
    __attrs = ['Policy','SecondaryPolicy','Name'] 
 
    def __init__(self, **kwargs): 
        for attr in self.__attrs: 
            setattr(self, attr, kwargs.get(attr, None)) 
 
    def __repr__(self): 
        return ', '.join( 
            ['%s: %r' % (attr, getattr(self, attr)) for attr in self.__attrs])   
 
    def __cmp__(self):      
        if self.Name != other.Name:   

请您参考如下方法:

对于 Python 2.x

我认为您需要为存储 API 数据的类实现 __cmp__。

对于 Python 3.x

我认为您需要为存储 API 数据的类实现 __eq__ 和 __hash__。

无论哪个版本的 Python,您都可以使用 comparator/eq 方法来检查列表中的重复项。如果您定义了 __eq__,这可以通过使用 set(list) 来完成。集合是唯一对象的列表。