📜  python 检查列表包含另一个列表 - Python (1)

📅  最后修改于: 2023-12-03 15:19:10.612000             🧑  作者: Mango

Python 检查列表包含另一个列表

在Python中,我们可以使用一些简单的代码来检查一个列表是否包含另一个列表。这在编程中很常见,尤其是在处理数据时。

方法一:使用 all() 函数
list1 = [1, 2, 3, 4, 5, 6]
list2 = [2, 4, 6]

if all(elem in list1 for elem in list2):
    print("List2 is a subset of List1")
else:
    print("List2 is not a subset of List1")

上述代码中,我们使用了Python内置的 all() 函数,它接受一个列表,并在这个列表中检查所有元素是否为True。

在这个例子中,我们使用 all() 函数来检查 list2 中的所有元素是否都在 list1 中。如果是,那么list2就是list1的子集。如果不是,它就不是list1的子集。

方法二:使用 set() 函数
list1 = [1, 2, 3, 4, 5, 6]
list2 = [2, 4, 6]

set1 = set(list1)
set2 = set(list2)

if set2.issubset(set1):
    print("List2 is a subset of List1")
else:
    print("List2 is not a subset of List1")

这里,我们先将list1和list2转换成set,然后使用issubset()函数来检查它们是否是子集。如果list2是list1的子集,那么它们的交集将是list2,也就是它们的并集将是list1。