使用交集时出现“不在列表中”错误

2024-09-30 08:19:11 发布

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

我正在尝试使用以下代码查找两个列表之间的匹配:

 def matching(text, symples, half2):
  for word in text:
    find = set(symples).intersection(word)

 indexNum = symples.index(find)
 print(indexNum)
 print(find)

我成功地找到了他们之间的匹配。我需要在列表中找到匹配单词的索引号,并且当我尝试在列表中找不到该单词时,会收到一条错误消息。你知道吗

我试着在两个列表find之间打印匹配的单词,它是用括号({}[])打印的。你知道吗

括号是列表中找不到匹配项的原因吗?你知道吗


Tags: 代码textin列表fordeffind单词
1条回答
网友
1楼 · 发布于 2024-09-30 08:19:11

你的代码不起作用有几个原因,括号就是其中一个原因。你知道吗

find = set(symples).intersection(word)返回set并将其赋值给变量find。稍后,当您尝试查找find的索引时,由于列表中找不到该集,因此找不到该索引。你知道吗

例如:

symples = ['1','2','3']
word = '1'
find = set(symples).intersection(word) # find = {'1'}
indexNum = symples.index(find)         # not found because {'1'} is not in the list

要解决此问题,请通过交叉点集进行循环:

find = set(symples).intersection(word)
for f in find:
    indexNum = symples.index(f)
    print(indexNum)
    print(f)

代码中的缩进也有很多问题。for循环一直在运行,因此find只设置了最后一个单词的交集。如果你想打印出每一个,确保你有正确的缩进。下面是一个示例,前面的错误也已修复:

def matching(text, symples, half2):
    for word in text:
        find = set(symples).intersection(word)
        for f in find:
            indexNum = symples.index(f)
            print(indexNum)
            print(f)

然而,有更好的方法来实现这一点。。。你知道吗

  1. 只走一次十字路口。你知道吗

    没有理由在文本中循环,每次都选择交叉点。马上把这两张单子的交集取出来。你知道吗

    def matching(text, symples, half2):
        find = set(symples).intersection(text)
        for f in find:
            indexNum = symples.index(f)
            print(indexNum)
            print(f)
    
  2. 循环浏览一个列表并检查每个单词是否在另一个列表中。你知道吗

    def matching(text, symples, half2):
        for word in symples:
            if word in text:
                indexNum = symples.index(word)
                print(indexNum)
                print(word)
    
  3. 循环浏览一个列表并检查每个单词是否在另一个列表中,同时跟踪索引。你知道吗

    def matching(text, symples, half2):
        for indexNum, word in enumerate(symples):
            if word in text:
                print(indexNum)
                print(word)
    

相关问题 更多 >

    热门问题