在 Python 中检查一个列表是否是其他列表的子集

pythonserver side programmingprogramming更新于 2025/12/26 2:20:17

在文本分析和其他各种数据分析领域中,经常需要查找给定列表是否已经是更大列表的一部分。在本文中,我们将看到实现此要求的 Python 程序。

使用 all

我们使用 for 循环来检查较小列表的每个元素是否存在于较大列表中。all 函数确保每个评估都返回 true。

示例

Alist = ['Mon','Tue', 5, 'Sat', 9]
Asub_list = ['Tue',5,9]

# 给定列表和子列表
print("Given list ",Alist)
print("Given sublist",Asub_list)

# 使用 all
if (all(x in Alist for x in Asub_list)):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")

# 再次检查
Asub_list = ['Wed',5,9]
print("New sublist",Asub_list)
if (all(x in Alist for x in Asub_list)):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")

输出

运行上述代码得到以下结果 −

Given list ['Mon', 'Tue', 5, 'Sat', 9]
Given sublist ['Tue', 5, 9]
Sublist is part of bigger list
New sublist ['Wed', 5, 9]
Sublist is not part of bigger list

使用子集

在这种方法中,我们将列表转换为集合,并使用子集函数来验证小列表是否是大列表的一部分。

示例

Alist = ['Mon','Tue', 5, 'Sat', 9]
Asub_list = ['Tue',5,9]

# 给定列表和子列表
print("Given list ",Alist)
print("Given sublist",Asub_list)

# 使用 all
if(set(Asub_list).issubset(set(Alist))):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")

# 再次检查
Asub_list = ['Wed',5,9]
print("New sublist",Asub_list)
if(set(Asub_list).issubset(set(Alist))):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")

输出

运行上述代码得到以下结果 −

Given list ['Mon', 'Tue', 5, 'Sat', 9]
Given sublist ['Tue', 5, 9]
Sublist is part of bigger list
New sublist ['Wed', 5, 9]
Sublist is not part of bigger list

使用交集

交集函数查找两个集合之间的共同元素。在这种方法中,我们将列表转换为集合并应用交集函数。如果交集的结果与子列表相同,则我们得出结论,子列表是列表的一部分。

示例

Alist = ['Mon','Tue', 5, 'Sat', 9]
Asub_list = ['Tue',5,9]

# 给定列表和子列表
print("Given list ",Alist)
print("Given sublist",Asub_list)

# 使用 all
if(set(Alist).intersection(Asub_list)== set(Asub_list)):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")

# 再次检查
Asub_list = ['Wed',5,9]
print("New sublist",Asub_list)
if(set(Alist).intersection(Asub_list)== set(Asub_list)):
   print("Sublist is part of bigger list")
else:
   print("Sublist is not part of bigger list")

输出

运行上述代码得到以下结果 −

Given list ['Mon', 'Tue', 5, 'Sat', 9]
Given sublist ['Tue', 5, 9]
Sublist is part of bigger list
New sublist ['Wed', 5, 9]
Sublist is not part of bigger list

相关文章


有用资源