You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python循环输出列表中含用户指定字母的单词?

修正Python单词筛选代码的逻辑错误

你需要实现的功能是:接收用户输入的字母,通过for循环输出单词列表中包含该字母的所有单词。现有代码的最后三行存在逻辑错误,同时还有一处文件调用的小问题,以下是修正后的完整代码及错误说明:

修正后的完整代码

import os.path

def name_file():
    # 询问用户文件名
    file_name = input("What is the name of the file to read the names from?")
    while not os.path.exists(file_name):
        print("This file does not exist")
        file_name = input("What is the name of the file to read the names from?")
    return file_name

# 保存用户输入的文件名并打开
file_name = name_file()
file_opener = open(file_name, "r")
read_line_by_line = file_opener.readlines()

word_list = []

for line in read_line_by_line:
    word_list.append(line.strip())
print(word_list)

letter = input("Pick a letter of your choosing and every word with that letter will be outputted: ")
# 遍历单词列表,筛选包含目标字母的单词
for word in word_list:
    # 统一转小写实现不区分大小写的匹配
    if letter.lower() in word.lower():
        print(word)

原代码的问题说明

  1. 变量名冲突:原循环for letter in word_list覆盖了用户输入的letter变量,导致丢失了目标筛选字母,这里改为for word in word_list避免冲突。
  2. 判断逻辑错误:原代码print(letter in word_list)是判断当前单词是否存在于列表中(结果永远为True),而非判断单词是否包含目标字母,修正为检查letter是否在word中。
  3. 大小写不兼容:新增了lower()方法统一转换为小写,确保用户输入大写字母时也能匹配到包含小写对应字母的单词。
  4. 文件调用冗余:原代码调用name_file()但未使用返回的文件名,硬编码打开了固定文件,修正为使用用户输入的文件名,符合函数设计的意图。

内容的提问来源于stack exchange,提问作者Alias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 18:50:31