检查一个列表是否是Python中其他列表的子集
在文本分析和数据分析的其他各个领域中,通常需要查找给定列表是否已经是更大列表的一部分。在本文中,我们将看到实现此要求的python程序。
所有
我们使用for循环来检查较小列表中的每个元素是否在较大列表中。all函数可确保每次评估返回true。
示例
Alist = ['Mon','Tue', 5, 'Sat', 9]
Asub_list = ['Tue',5,9]
# Given list and sublist
print("Given list ",Alist)
print("Given sublist",Asub_list)
# With 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")
# Checkign again
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]
# Given list and sublist
print("Given list ",Alist)
print("Given sublist",Asub_list)
# With all
if(set(Asub_list).issubset(set(Alist))):
print("Sublist is part of bigger list")
else:
print("Sublist is not part of bigger list")
# Checkign again
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]
# Given list and sublist
print("Given list ",Alist)
print("Given sublist",Asub_list)
# With 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")
# Checkign again
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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短