Python - 检查一个列表是否包含在另一个列表中
给定两个不同的 python 列表,我们需要确定第一个列表是否是第二个列表的一部分。
使用 map 和 join
我们可以首先应用 map 函数以获取列表元素,然后应用 join 函数创建以逗号分隔的值的列表。接下来,我们使用 in 运算符以确定第一个列表是否是第二个列表的一部分。
示例
listA = ['x', 'y', 't']
listB = ['t', 'z','a','x', 'y', 't']
print("Given listA elemnts: ")
print(', '.join(map(str, listA)))
print("Given listB elemnts:")
print(', '.join(map(str, listB)))
res = ', '.join(map(str, listA)) in ', '.join(map(str, listB))
if res:
print("List A is part of list B")
else:
print("List A is not a part of list B")输出
运行上述代码后,会得到以下结果 -
Given listA elemnts: x, y, t Given listB elemnts: t, z, a, x, y, t List A is part of list B
使用 range 和 len
我们可以设计一个 for 循环来检查表单的一个列表中的元素是否存在于另一个列表中,方法是使用 range 函数和 len 函数。
示例
listA = ['x', 'y', 't']
listB = ['t', 'z','a','x', 'y', 't']
print("Given listA elemnts: \n",listA)
print("Given listB elemnts:\n",listB)
n = len(listA)
res = any(listA == listB[i:i + n] for i in range(len(listB) - n + 1))
if res:
print("List A is part of list B")
else:
print("List A is not a part of list B")输出
运行上述代码后,会得到以下结果 -
Given listA elemnts: ['x', 'y', 't'] Given listB elemnts: ['t', 'z', 'a', 'x', 'y', 't'] List A is part of list B
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP