简体   繁体   English

从列表列表中删除子列表

[英]Removing sublists from a list of lists

I'm trying to find the fastest way to solve this problem, say I have a list of lists: 我正试图找到解决这个问题的最快方法,比如我有一个列表列表:

myList = [[1,2,3,4,5],[2,3],[4,5,6,7],[1,2,3],[3,7]]

I'd like to be able to remove all the lists that are sublists of one of the other lists, for example I'd like the following output: 我希望能够删除作为其他列表之一的子列表的所有列表,例如我想要以下输出:

myList = [[1,2,3,4,5],[4,5,6,7],[3,7]]

Where the lists [2,3] and [1,2,3] were removed because they are completely contained in one of the other lists, while [3,7] was not removed because no single list contained all those elements. 列表[2,3]和[1,2,3]被删除,因为它们完全包含在其他一个列表中,而[3,7]没有删除,因为没有一个列表包含所有这些元素。

I'm not restricted to any one data structure, if a list of lists or a set is easier to work with, that would be fine too. 我不限于任何一个数据结构,如果列表或集合列表更容易使用,那也没关系。

The best I could come up with was something like this but it doesn't really work because I'm trying to remove from a list while iterating over it. 我能想到的最好的东西是这样的,但它并没有真正起作用,因为我试图在迭代它时从列表中删除。 I tried to copy it into a new list but somehow I couldn't get it working right. 我试图将它复制到一个新的列表,但不知怎的,我无法让它正常工作。

for outter in range(0,len(myList)):
outterSet = set(myList[outter])
for inner in range(outter,len(myList)):
    innerSet = set(myList[inner])
    if innerSet.issubset(outterSet):
        myList.remove(innerSet)

Thanks. 谢谢。

The key to solving your problem is a list of sets: 解决问题的关键是集合列表:

lists = [[1,2,3,4,5],[2,3],[4,5,6,7],[1,2,3],[3,7]]

sets = [set(l) for l in lists]

new_list = [l for l,s in zip(lists, sets) if not any(s < other for other in sets)]

This converts the inner lists to sets, compares each set to every other set to see if it is contained within it (using the < operator) and, if it is not strictly contained within another set, adds the original list to the new list of lists. 这将内部列表转换为集合,将每个集合与每个其他集合进行比较以查看它是否包含在其中(使用<运算符),如果它未严格包含在另一个集合中,则将原始列表添加到新的列表中名单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM