如果列表中的元素是另一个没有内置函数的列表的子集,则python将进行搜索

2024-05-17 15:07:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图搜索一个列表中的元素是否是另一个列表的子集,而不使用诸如“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)

Tags: 函数代码in元素列表indexifitem
2条回答

问题

您的代码将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')

这可用于查找主列表中是否包含子列表的所有元素。你知道吗

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

相关问题 更多 >