首页 > 解决方案 > 如何在python中找到一个列表而不是另一个列表的子列表?

问题描述

我需要比较两个基本上是列表列表的列表,找出存在于一个列表中但不存在于其他列表中的子列表。子列表的排列也不考虑即['a','b'] = ['b,'a']。这两个列表是

List_1 = [['T_1','T_2'],['T_2','T_3'],['T_1','T_3']]
List_2 = [['T_1','T_2'],['T_3','T_1']]

输出列表应该是

out_list = [['T_2','T_3']]

标签: pythonlistsublist

解决方案


对于两个元素子列表,这应该足够了:

[x for x in List_1 if x not in List_2 and x[::-1] not in List_2]

代码

List_1 = [['T_1','T_2'],['T_2','T_3'],['T_1','T_3']]
List_2 = [['T_1','T_2'],['T_3','T_1']]

print([x for x in List_1 if x not in List_2 and x[::-1] not in List_2])

推荐阅读