从列表列表中删除子列表 [英] Removing sublists from a list of lists

查看:362
本文介绍了从列表列表中删除子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到解决此问题的最快方法,比如说我有一个列表列表:

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]]

删除列表[2,3]和[1,2,3]是因为它们完全包含在其他列表之一中,而没有删除[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.

我不限于任何一种数据结构,如果列表或集合的列表更易于使用,那也可以.

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)

谢谢.

推荐答案

解决问题的关键是设备列表:

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.

这篇关于从列表列表中删除子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆