我正在尝试搜索列表中的元素是否是另一个列表的子集,而不使用“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
错误。
解决方案:
def letterSearch(sublist,mainlist):
x = 0
index = 0
while x < len(mainlist):
if len(sublist) != index and sublist[index] == mainlist[x]:
index = index + 1
x += 1
if len(sublist) == index:
return index
x = ['d','g']
y = ['d','g','a','b']
index = letterSearch(x,y)
print(index) # 2
# To display if x is a subset of y or not:
if index:
print('{} is a subset of {}'.format(x, y))
else:
print('Not a subset')
关于python 搜索列表中的元素是否是另一个列表的子集,无需内置函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49571907/