"Not in list" 使用交集时出错

"Not in list" error while using intersection

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

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

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

我成功找到了他们之间的匹配。我需要在列表中找到匹配词的索引号,当我尝试这样做时,我收到一条错误消息,指出在列表中找不到该词。

我试图打印两个列表 find 之间的匹配词,结果打印时带有方括号( {}[] )。

方括号是在列表中找不到匹配项的原因吗?

您的代码无法正常工作的原因有很多,您认为括号是原因之一是正确的。

find = set(symples).intersection(word)returns并将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)