给定两个不同的python列表,我们需要查找第一个列表是否为第二个列表的一部分。

与映射并加入

我们可以首先应用map函数来获取列表的元素,然后应用join函数来确定逗号分隔的值列表。接下来,我们使用in运算符来查找第一个列表是否是第二个列表的一部分。

示例listA = ['x', 'y', 't']

listB = ['t', 'z','a','x', 'y', 't']

print("Given listA elemnts: ")

print(', '.join(map(str, listA)))

print("给定listB元素:")

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

给定listB元素:

t, z, a, x, y, t

List A is part of list B

随着范围和镜头

我们可以设计一个for循环,使用range函数和len函数检查一个列表中另一个列表中元素的存在。

示例listA = ['x', 'y', 't']

listB = ['t', 'z','a','x', 'y', 't']

print("Given listA elemnts: \n",listA)

print("给定listB元素:\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']

给定listB元素:

['t', 'z', 'a', 'x', 'y', 't']

List A is part of list B

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐