在Python中获得独特的价值

时间:2015-02-27 06:32:55

标签: python mysql list distinct

我有一个清单

[<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循环来做同样的事情?

mycode的

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

3 个答案:

答案 0 :(得分:1)

这应该很好地处理事情。

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

答案 1 :(得分:0)

试试这个:

newList = list(set(oldList))

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

有关详细信息,请参阅this。如果有帮助的话,请参阅。

答案 2 :(得分:0)

在所有试验和错误之后,我回到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))]

Snippet礼貌:@Richard