2012-07-09 98 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