需要帮助来创建一个函数,该函数将从给定列表中建议单词



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

基本上,如果输入是"那么输出将是"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())

这是由于试图访问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所提到的,实际上有一个内置函数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())

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

你的循环逻辑是为word而不是letter构建的。修改:

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

最新更新