【问题标题】:Need help to create a function that will suggest words from a given list需要帮助来创建一个可以从给定列表中建议单词的函数
【发布时间】:2021-02-10 06:12:06
【问题描述】:

我想创建一个函数,它接收一个包含一堆单词的列表,然后我会给出半个单词,它会给我整个单词。

基本上,如果输入是“ca”,那么输出将是“car”或“win”给出“window”等等。我的想法是遍历我输入的单词中的每个字母并检查它是否匹配。

在下面的代码中,我尝试做的是首先遍历单词和单词中的每个字母,然后遍历列表,然后我尝试 匹配两个字母。如果匹配,它将打印该单词。但我收到错误消息string index out of range

我觉得只匹配两个字母根本不是最佳选择,如果列表更长,比如字典,可能会导致问题。

list_words = ["car","telephone","watch","window","laptop","lamp"]
word = "ca"
def autocomplete():
    for letter in word:
        i = 0
        while i < len(list_words):
            if letter[0] == list_words[i][0] and letter[1] == list_words[i][1]:
                return list_word[i]
            i += 1
print(autocomplete())

【问题讨论】:

  • 如果你使用startswith(),你真的可以简化这个。
  • 哇,我什至不知道有这个,非常感谢,我会试试看。

标签: python


【解决方案1】:

这是由于尝试访问 letter[1] 而引起的。由于for letter in word 循环,letter 被设置为包含来自word 的单个字母的字符串,因此letter[1] 将导致错误。

很可能,您打算访问word[0]word[1],而不是letter[0]letter[1]。试试下面的代码:

list_words = ["car","telephone","watch","window","laptop","lamp"]
word = "ca"
def autocomplete():
    for letter in word:
        i = 0
        while i < len(list_words):
            if word[0] == list_words[i][0] and word[1] == list_words[i][1]:
                return list_words[i]
            i += 1
print(autocomplete())

通过执行此更改,您甚至不再需要 for letter in word 循环,因此您可以将代码更改为:

list_words = ["car","telephone","watch","window","laptop","lamp"]
word = "ca"
def autocomplete():
    i = 0
    while i < len(list_words):
        if word[0] == list_words[i][0] and word[1] == list_words[i][1]:
            return list_words[i]
        i += 1
print(autocomplete())

作为 Random Davis mentioned,实际上有一个内置函数 startswith,可以进一步简化您的代码。在下面的代码中,它不会检查word 的第一个和第二个字符是否与list_words[i] 的第一个和第二个字符匹配,而是简单地检查list_words[i] 是否以word 开头。

list_words = ["car","telephone","watch","window","laptop","lamp"]
word = "ca"
def autocomplete():
    i = 0
    while i < len(list_words):
        if list_words[i].startswith(word):
            return list_words[i]
        i += 1
print(autocomplete())

【讨论】:

  • 该死的,感谢您的帮助,非常感谢
【解决方案2】:

letter 是部分单词的单个字母,正如您指定的那样。 当你检查 letter[1] 时,你认为你会得到什么?这超出了范围。

您的循环逻辑是为word 构建的,而不是为letter 构建的。要解决这个问题:

for match in list_words:
    if match.startswith(word):
        return match
return "FAILED"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 2020-06-08
    相关资源
    最近更新 更多