我试图搜索一个列表中的元素是否是另一个列表的子集,而不使用诸如“set”或“if item in list”之类的内置函数。我有以下代码,但我不断得到错误的'索引超出范围'
def letterSearch(sublist,mainlist):
x = 0
index = 0
while x < len(mainlist):
if sublist[index] == mainlist[x]:
index = index + 1
x = x + 1
else:
x = x + 1
x = ['d','g']
y = ['d','g','a','b']
letterSearch(x,y)
print(index)
问题:
您的代码将
index
值的增量超过sublist
的长度。所以下次比较时,该索引中没有导致index out of range
错误的项。你知道吗解决方案:
这可用于查找主列表中是否包含子列表的所有元素。你知道吗
相关问题 更多 >
编程相关推荐