0

我有许多可以“打开”或“关闭”的列表,如下所示:

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)

当子列表关闭时,是否有一种简单的算法可以从主列表中删除项目?目标是不删除属于仍然打开的其他列表的项目。

4

2 回答 2

2

You have to keep track of how many lists each item was from. The simplest way to do that is with a map. I like to use collections.Counter for something like this.

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)

In addition, you can get rid of all_open altogether and use the count.keys() iterator instead.

于 2012-06-23T00:24:37.573 回答
0

Something like

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]

I believe this will results in what you desire although I'm not too clear if that's what you are asking for. You could also keep track of how many times each item is open, and when you close a list, decrease that by 1. If the value is 0, then remove an item. Might be a lot more efficient than this.

于 2012-06-23T00:25:48.567 回答