此函数将从 .txt 文件的列表中搜索字谜词,我希望能够检查字谜词并返回我输入的单词的所有字谜词,如果它不是字谜词,它将返回输入,当我在下面的代码中执行此操作时,它会迭代 for 循环,然后忽略我的第一个 if 语句并直接转到我的 else 语句。我该如何解决这个问题?
def find_in_dict():
input_word = input("Enter input string)")
sorted_word = ''.join(sorted(input_word.strip()))
a_word = ''.join((input_word.strip()))
word_file = open("filename", "r")
word_list = {}
for text in word_file:
simple_text = ''.join(sorted(text.strip()))
word_list.update({text.strip(): simple_text})
alist = []
for key, val in word_list.items():
if val == sorted_word:
alist.append(key)
return alist
else:
return "No words can be formed from:" + a_word
最佳答案
您正在 if 和 else 分支中创建一个 return
语句,这将破坏 for (因为在函数内部调用的 return
正是这样做的,中断执行并返回值),所以,不要这样做,只是询问单词是否相等,最后检查是否没有出现(空列表)
for text in word_file:
simple_text = ''.join(sorted(text.strip()))
word_list.update({text.strip(): simple_text})
alist = []
for key, val in word_list.items():
if val == sorted_word:
alist.append(key)
if alist == []: print("No words can be formed from: " + a_word)
关于python - 字谜代码错误 : python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46983056/