在Python中获取不同的值

2024-10-01 02:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子

[<Storage {'CaseID': 45L, 'PatientProfile_ID': 3L}>, 
<Storage {'CaseID': 46L, 'PatientProfile_ID': 2L}>,
<Storage {'CaseID': 45L, 'PatientProfile_ID': 3L}>,
<Storage {'CaseID': 45L, 'PatientProfile_ID': 3L}>, 
<Storage {'CaseID': 46L, 'PatientProfile_ID': 2L}>, 
<Storage {'CaseID': 45L, 'PatientProfile_ID': 3L}>, 
<Storage {'CaseID': 46L, 'PatientProfile_ID': 2L}>, 
<Storage {'CaseID': 45L, 'PatientProfile_ID': 3L}>, 
<Storage {'CaseID': 45L, 'PatientProfile_ID': 3L}>, 
<Storage {'CaseID': 45L, 'PatientProfile_ID': 3L}>, 
<Storage {'CaseID': 45L, 'PatientProfile_ID': 3L}>, 
<Storage {'CaseID': 46L, 'PatientProfile_ID': 2L}>, 
<Storage {'CaseID': 45L, 'PatientProfile_ID': 3L}>]

我想要这个的独特价值 预期结果是

[
 <Storage {'CaseID': 45L, 'PatientProfile_ID': 3L}>, 
 <Storage {'CaseID': 46L, 'PatientProfile_ID': 2L}>
]

正在从数据库中提取此数据。请不要建议我在数据库中使用DISTINCT关键字。它已被另一列排序。使用distinct将删除排序结果。你知道吗

可以用python实现。或者我必须写一个for循环来做同样的事情吗?你知道吗

霉菌代码

entries=db.query("SELECT cases.ID as CaseID,PatientProfile_ID FROM \
                             `callog` ,consultation,cases WHERE callog.Consultation_ID=consultation.ID and consultation.Case_ID = cases.ID and \
                             Doctor_ID="+str(Id)+" ORDER BY callog.CallDate DESC")
            rows=entries.list()
            return rows

Tags: and数据id数据库排序storagerows单子
3条回答

试试这个:

newList = list(set(oldList))

上面,将您的列表转换为一个集合(删除重复项),然后再返回到一个列表中。你知道吗

有关更多信息,请参阅this。看,如果有帮助的话。你知道吗

这应该处理得很好。你知道吗

def remove_dupes_keep_order(seq):
  seen = set()
  seen_add = seen.add
  return [ x for x in seq if not (x in seen or seen_add(x))]

使用seen_add可以加速操作。你知道吗

另见this SO question。你知道吗

由于问题似乎是您的项目属于Storage类型,请尝试以下操作:

def remove_dupes_keep_order(seq):
  seen = set()
  seen_add = seen.add
  return [ x for x in seq if not (json.dumps(x, sort_keys=True) in seen or seen_add(json.dumps(x, sort_keys=True)))]

在经历了所有的尝试和错误之后,我又回到了For循环

def remove_dupes_keep_order(self,seq):
        Lister=[]
        for row in seq:
            Dicter={"CaseID":row["CaseID"],"PatientProfile_ID":row["PatientProfile_ID"]}
            Lister.append(Dicter)
        seen = []
        seen_add = seen.append
        return [ x for x in Lister if not (x in seen or seen_add(x))]

片段礼貌:@Richard

相关问题 更多 >