我尝试搜索列表中的元素是否是另一个列表的子集而不使用内置函数,例如' set'或者如果列表中有项目'。我有以下代码,但我一直在错误地指出' index超出范围'
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)
答案 0 :(得分:1)
<强>问题强>:
您的代码会增加超出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')
答案 1 :(得分:0)
这可用于查找子列表中的所有元素是否都包含在主列表中。
def letterSearch(subList, mainList):
for i in subList:
found = False
for j in mainList:
if j == i:
found = True
if not found:
return False
return True