从主列表中查找许多唯一的子列表

时间:2017-04-21 03:46:40

标签: python list sublist

我有一个这样的清单:

original = [1, 2, 3, 4]

另一个我将找到子列表:

queries = [1, 4, 1, 5, 2, 3, 2, 1]

我希望所有子列表只包含原始列表的一个实例。所以在这个例子中,我会得到:

sublists = [ [1, 2, 3, 4], [1, 2], [1] ]

我的原件将留下:

original = [5]

我将如何实现这一目标?谢谢

1 个答案:

答案 0 :(得分:0)

一种稍微间接的方法是使用collections.Counter库对象:

from collections import Counter
from itertools import zip_longest, repeat

original = [1, 2, 3, 4]
query = [1, 4, 1, 5, 2, 3, 2, 1]

cnts = Counter(query)
# cnts: Counter({1: 3, 2: 2, 4: 1, 5: 1, 3: 1})
sublists = zip_longest(*map(repeat, original, map(cnts.pop, original)))
# this creates the approprate number of copies of 1, 2, 3, 4 and (via
# zip_longest) shuffles them into lists with max one occurrence each
# sublists are padded with None's -- [(1, 2, 3, 4), (1, 2, None, None), (1, None, None, None)]
sublists = list(map(list, map(filter, repeat(bool), sublists)))
# None's are removed -- [[1, 2, 3, 4], [1, 2], [1]]
leftovers = list(filter(cnts.__contains__, query))
# [5]