【问题标题】:python search if elements in a list are a subset of another list without built in functionspython搜索列表中的元素是否是另一个列表的子集而没有内置函数
【发布时间】:2018-03-30 09:32:36
【问题描述】:

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

【问题讨论】:

  • len() 是一个内置函数
  • len() 没问题,抱歉我的意思更像是内置搜索功能

标签: python list search


【解决方案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')

【讨论】:

    【解决方案2】:

    这可用于查找子列表的所有元素是否都包含在主列表中。

    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
    

    【讨论】:

    • 谢谢!我只是想知道为什么最底部的'return True'是必需的??
    • 这是必要的,因为如果不包含 subList 的元素,该函数返回 False,否则返回 True。如果在包含所有元素的情况下省略 return True 语句,则函数将返回 None ,因为不会命中 return 语句。您获得了一个返回 None 或 False 的函数,我认为这不是一个好主意,但如果您知道这种行为,您可以随意使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多