python - 字谜代码错误 : python

标签 python

此函数将从 .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/

相关文章:

python - 使用 Selenium Python 填充验证码

python - Blackjack 风格的 Python(计算机)游戏循环不正确

python - 尝试在非包 python 中进行相对导入

python - 在 Python 中模拟 Google App Engine 文件上传

python - 录制和播放从麦克风录制的音频流

Python 无法通过命令行处理导入

python - 将一个程序文件的结果输入到python中的另一个程序中

python - 在 docker 镜像中安装 R

python - 如何用另一个列表元素随机替换列表元素?

python - 虚拟环境 Python 2.4