【问题标题】:Getting Distinct value in Python在 Python 中获得不同的价值
【发布时间】:2015-04-29 19:15:05
【问题描述】:

我有一个清单

[<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

【问题讨论】:

  • set(ur_list) 操作会起作用。
  • @TanveerAlam 不保证物品的顺序
  • @thefourtheye:查看我的代码。这就是 webpy 返回结果集的方式。

标签: python mysql list distinct


【解决方案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)))]

【讨论】:

  • 不, at /doctor unhashable type: 'Storage'
  • 啊,那太糟糕了。您是否正在使用Storage 对象的功能?或者你能把它转换成标准的 Python 字典吗?
  • @AbhilashCherukat,我已经更新了我的答案以提供另一种可能性。
  • 网上不多说,只说Storage是一个Fancy type的字典:(
  • 我也没有看到太多,但也许你可以用dict(i_am_a_storage_object) 将其转换回来。
【解决方案2】:

试试这个:

newList = list(set(oldList))

在上面,将您的列表变成一个集合(删除重复项),然后再变成一个列表。

更多信息:请参阅this。看看,是否有帮助。

【讨论】:

  • 不, at /doctor unhashable type: 'Storage' 存储部分是两个答案的问题。
【解决方案3】:

经过所有的试验和错误,我回到了 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

【讨论】:

  • 这有一个 for 循环,您可以使用已接受的答案,因为它是一个更好的解决方案。
猜你喜欢
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2010-12-21
相关资源
最近更新 更多