python 搜索列表中的元素是否是另一个列表的子集,无需内置函数

标签 python list search

我正在尝试搜索列表中的元素是否是另一个列表的子集,而不使用“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/

相关文章:

python - 如何从 vesselfinder 重新创建坐标转换 (EPSG :4326 to EPSG:3857)?

python - 用于匹配非整数的 float 的正则表达式

python - 从Python中的链表中删除一个元素

python - 通过公共(public)标识符交叉识别(重叠)Python 中的两个列表

emacs - 使用 Emacs (windows) 和 GnuWin32 Grep 失败的 Grep

python - 如何从 pandas 数据框中清除前缀?

python - 计算 mongodb 数组中的元素数

list - 列表的 'maximum' 函数是否只能在单独的函数中工作?

MySQL - 如何执行此字符串搜索?

mysql - Netbeans 每行搜索 2 个术语