2012-06-23 80 views
0

我有許多可以「打開」列表或「關閉」,這樣的事情:Python的算法列表和子列表

lista = ["a", "b", "c"] 
listb = ["d", "e"] 
listc = ["a", "b", "e"] 
listd = ["c", "d"] 

我有所有打開的項目的主列表:

all_open = ["a", "b", "c", "e"] 

和開放列表的列表:

open_lists = ["lista", "listc"] 

由於子列表的雙頭呆,他們的項目將被添加到主列表:

open_lists.append("listb") 
for each i in listb: 
    if !(i in all_open): 
     all_open.append(i) 

是否有一個簡單的算法,當一個子列表關閉時,從主列表中刪除項目?目標是不要刪除屬於其他尚未打開的列表的項目。

+1

它是什麼意思**的列表或項目,「打開」? –

回答

2

你必須記錄每件物品來自多少個清單。最簡單的方法是使用地圖。我喜歡用collections.Counter這樣的東西。

import collections 
count = collections.Counter() 

# add a list 
for i in listb: 
    if count[i] == 0: 
     all_open.append(i) 
    count[i] += 1 

# delete a list 
for i in listb: 
    count[i] -= 1 
    if count[i] == 0: 
     all_open.remove(i) 

此外,你可以擺脫all_open乾脆使用count.keys()迭代器,而非。

+3

(請注意,這基本上是通常所說的「引用計數」,並且經常用於垃圾回收算法。) – Amber

+0

引用計數正是我所期待的。 – nathancahill

0

喜歡的東西

all_items = [] 
for l in open_lists: 
    for item in l: 
     if item not in all_items: 
      all_items.append(item) 

all_open = [item for item in all_open if item not in all_items] 

我相信這會在你的願望,雖然我不是太清楚,如果這是你所要求的結果。您還可以跟蹤每件物品打開的次數,以及關閉列表時,將其減少1.如果該值爲0,則刪除一件物品。可能比這更有效率。