2012-07-09 93 views
0

我想创建像facebook一样的通知。一切正常,但我有重复。例如,action = like,url = post/1我想要获取状态为1的所有通知 - 未读,并消除action和url相同的重复。在消除通知重复

if n_dup[i]['url'] == n_dup[j]['url'] and n_dup[i]['action'] == n_dup[j]

def recieve_notification(request): 
    t = loader.get_template('notifications.html') 
    nots = Notification.objects.filter(recipent=request.user, status=1, pub_date__gte=datetime.datetime.now()-datetime.timedelta(days=3)) 
    n_dup = [] #list of notifications with duplicates 
    for n in nots: 
     n_dup.append({'id':n.id, 'url':n.url, 'action':n.action}) 

    i = len(n_dup)-1 
    j = len(n_dup)-1  
    while j>=0: 
     while i>=0: 
      if n_dup[i]['url'] == n_dup[j]['url'] and n_dup[i]['action'] == n_dup[j]['action'] and i is not j: 
       del n_dup[i] 
      i-=1 
     j-=1 
     out_n = []  
     for n in n_dup: 
      n_id = n['id'] 
     out_n.append(Notification.objects.get(id=n_id)) 

    c = RequestContext(request, {'notifications':out_n, 'notifications_count':len(out_n)}) 
    return HttpResponse(t.render(c))` 

也许你是在更好地了解“列表索引超出范围”编写这一切的东西:你可以找到下面的代码我有这样的错误:

错误?

回答

4

在两个循环的第一次迭代中,j == i == len(n_dup)-1,所以n_dup[i] == n_dup[j]。它被认为是重复的并且被删除。在第二次迭代中,您将尝试访问不再存在的n_dub[len(n_dup)-1],因为您已将其删除。


如果我可以建议另一种方法,让偷懒,有蟒蛇为我们做了重复检测:

class Notification: 
    def __init__(self, id, url, action): 
     self.id = id 
     self.url = url 
     self.action = action 

    def __eq__(self, other): 
     return self.url == other.url and self.action == other.action 

    def __hash__(self): 
     return hash(self.url)^hash(self.action) 


unique_notifications = {Notification(n.id, n.url, n.action) for n in nots} 

我们定义了一个通知对象与方法来进行比较和计算散列(需要将它放入一个集合中),并创建一组通知。一组永远不会包含重复,所以你现在可以遍历集合!

您也可以将此方法添加到您的通知对象并直接使用它。然后你会写:

out_n = set(Notification.objects.filter(...)) 

加分:该集合用于删除重复的算法比您使用的算法效率高得多。

+0

awsome,thx伙计。 – user1403568 2012-07-09 18:51:54