我有一个单词“ MINORITY”,我想知道是否有一种简单的方法来检查单词列表中是否包含“ MINORITY”。但是,技巧部分在列表中,其中某些单词可能是我要查找的单词的子集。我的清单如下:
word = 'MINORITY'
list_words = ['HELLO','STACK','OVER','MINORIT','FLOW']
在这种情况下,我想获取索引3,因为'MINORIT'是'MINORITY'的子集
注意:我不想遍历单词列表,而是使用诸如'isin()'
的函数这是一个非常简单的解决方法,您可以使用名为difflib
的库在列表中搜索相似的单词。
word = 'MINORITY'
list_words = ['HELLO','STACK','OVER','MINORIT','FLOW']
import difflib
outcome = difflib.get_close_matches(word, list_words)
print(outcome)
如果您希望获得结果的索引,则可以执行list_words.index(outcome)
def check_member(word, lst):
" finds which index of lst is a substring of word (if any) "
return (i for i, x in enumerate(lst) if x in word)
Test
list_words = ['HELLO','STACK','OVER','MINORIT','FLOW']
for word in ['foo', 'MINORITY', 'minority', 'HELLO123', 'STACK', "12FLOW", 'bob']:
i = next(check_member(word, list_words), None)
if i:
print(f' {word} matches {list_words[i]} at index {i}')
else:
print(f'{word} - no matches')
输出
foo - no matches
MINORITY matches MINORIT at index 3
minority - no matches
HELLO123 - no matches
STACK matches STACK at index 1
12FLOW matches FLOW at index 4
bob - no matches