查找两个嵌套列表之间的差异

时间:2012-11-20 14:23:21

标签: python list

我有一个嵌套列表和另一个嵌套列表,它是第一个列表的子集:

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

2 个答案:

答案 0 :(得分:15)

使用列表理解:

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

答案 1 :(得分:5)

如果将列表列表转换为元组列表,则可以从它们创建集合并使用set difference operator:

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]

更快