【问题标题】:Find if a word is in list OR an element in the list is a subset of this word查找单词是否在列表中或列表中的元素是否是该单词的子集
【发布时间】:2020-03-24 14:24:02
【问题描述】:

我有一个单词“MINORITY”,我想知道是否有一种简单的方法可以检查单词“MINORITY”是否在单词列表中。但是,技巧部分是在列表中,其中一些单词可能是我正在查找的单词的子集。 我的清单如下:

word = 'MINORITY'

list_words = ['HELLO','STACK','OVER','MINORIT','FLOW']

在这种情况下,我想获得索引 3,因为“MINORIT”是“MINORITY”的子集

注意:我不想遍历单词列表,而是使用诸如“isin()”之类的函数

【问题讨论】:

  • 您的意思是某些词可能是子字符串(例如,'MINORIT' 是 'MINORITY' 的子字符串而不是子集)?

标签: python regex list lambda


【解决方案1】:

这是一个很容易解决的问题,您可以使用名为 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)

【讨论】:

    【解决方案2】:
    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)
    

    测试

    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
    

    【讨论】:

      猜你喜欢
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 2020-10-10
      相关资源
      最近更新 更多