我有一个嵌套列表和另一个嵌套列表,它是第一个列表的子集:
lst = [[1, 2], [3, 4], [1, 2], [5, 6], [8, 3], [2, 7]]
sublst = [[1, 2], [8, 3]]
如何找到不在子列表中的内部列表。使用上述示例所需的输出是:
diff = [[3, 4], [5, 6], [2, 7]]
使用列表推导:
In [42]: lst = [[1, 2], [3, 4], [1, 2], [5, 6], [8, 3], [2, 7]]
In [43]: sublst = [[1, 2], [8, 3]]
In [44]: [x for x in lst if x not in sublst]
Out[44]: [[3, 4], [5, 6], [2, 7]]
或filter()
:
In [45]: filter(lambda x:x not in sublst,lst)
Out[45]: [[3, 4], [5, 6], [2, 7]]
如果将
列表列表转换为元组列表,则可以从它们创建集合并使用集合差分运算符:
lst = [[1, 2], [3, 4], [1, 2], [5, 6], [8, 3], [2, 7]]
sublst = [[1, 2], [8, 3]]
def tuples(lst): return [tuple(l) for l in lst]
print set(tuples(lst)) - set(tuples(sublst))
将打印:
set([(5, 6), (2, 7), (3, 4)])
对于庞大的列表,它可能比评估[x for x in lst if x not in sublst]
更快