有没有一种方法可以在Python中组合两个列表进行搜索?

2024-05-03 20:47:19 发布

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

我想不出一个题目,但我可以解释。假设用户必须输入一个包含两个单词的字符串。然而,有多种方法来书写每一个单词。比如:

words = input("Enter 'Hello World' however you want to type it ")
possibilities = [
    "Hello World",
    "hello World",
    "Hello world",
    "hello world",
    "Helo World",
    "helo World",
    "Helo world",
    "helo world"
]
if words in possibilities:
    print("true")

注意:

我知道这个具体的例子可以通过键入words.lower()来解决,而且你知道helo会是一个严重的打字错误,这只是一个例子。

有没有办法这样做

words = input("Enter 'Hello World' however you want to type it ")
firstWord = [
    "Hello",
    "hello",
    "Helo",
    "helo"
]
secondWord = [
    "World",
    "world",
]
words = words.split(' ')
if words[0] in firstWord and words[1] in secondWord:
    print("true")

Tags: toinyouhelloworldinput单词words
2条回答

回答问题时,可以使用itertools.product生成两个列表的所有组合

from itertools import product


if words in [' '.join(t) for t in product(firstWord, secondWord)]:
    print("true")

这可以扩展到:

parts = [["h", "H"], ["ello", "elo"], [" "], ["W", "w"], ["orld"]]
if words in [''.join(t) for t in product(*parts)]:
    print("true")

使用Levenshtein distance

请参见https://tedboy.github.io/nlps/generated/generated/nltk.edit_distance.html#nltk-edit-distance作为python库的示例,该库将计算“Hello”和“helo”之间的距离

相关问题 更多 >