我有2个列表作为list<list<list>>
列表,我想检查其中一个是否是另一个的子集。
list_1 = [
[
[1,2],[2,3]
],
[
[3,4],[5,6]
]
]
list_2 = [
[
[3,4], [5, 6]
]
]
所以预期输出是因为list2有[[[3,4]]],它是list_1的一部分所以它应该是一个子集。
list_1有2个元素,第二个元素与list_2中的第一个元素匹配,因此list_2是list_1的子集。
比较不是在元素级别,而是在列表级别。
我尝试了set(list_2) < set(list_1)
,但结果是unhashable type: list
。那我怎么能达到上述比较呢?
你可以迭代list_2
并检查它的元素是否包含在list_1
中:
list_1 = [[[1, 2], [2, 3]], [[3, 4], [5, 6]]]
list_2 = [[[3, 4], [5, 6]]]
all(x in list_1 for x in list_2) # Option 1.
all(map(list_1.__contains__, list_2)) # Option 2.
第二个版本适用于列表(和其他类型),但a in b
更通用,因为如果没有定义b.__iter__
,它会回退到b.__contains__
。
集合不能保存列表,因为集合依赖于它们的元素是不可变的,列表是可变的。如果将列表切换为元组,它将起作用:
list_1 = [(1,2), (2,3), (3,4)]
list_2 = [(2,3), (3,4)]
set(list_2) < set(list_1)
您还可以将外部列表更改为元组,但我将它们保留为列表以明确哪些应该是元组。
您有嵌套列表,因此简单的比较将不起作用。这是一个函数,检查l2是否是l1的子集:
list_1 = [[[1,2],[2,3],[3,4]]]
list_2 = [[[2,3],[3,4]]]
def comparison_nested_lists(l1,l2):
l1,l2 = l1[0],l2[0]
l2_in_l1 = True
for i in l2:
if i not in l1:
l2_in_l1 = False
return l2_in_l1
print comparison_nested_lists(list_1,list_2)