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

Python程序调试:实现按字母顺序输出字符串范围判定结果

问题分析

原代码将符合范围的字符串与不符合的字符串分别存入两个列表后单独输出,导致整体结果无法按字母顺序排列。需要调整逻辑,先对所有读取到的字符串进行排序,再逐个判断输出。

修正后的代码

file_name = input()
lower = input()
upper = input()

# 使用with语句自动管理文件资源
with open(file_name) as user_file:
    # 读取所有行并去除换行符,同时生成排序后的列表
    word_list = sorted(word.strip('\n') for word in user_file.readlines())

# 遍历排序后的列表,逐个判断并输出结果
for word in word_list:
    if lower <= word <= upper:
        print(f"{word} - in range")
    else:
        print(f"{word} - not in range")
# 确保结尾换行
print()

修改说明

  • 移除原代码中new_list和bad_list的拆分逻辑,改为直接对所有处理后的字符串使用sorted()函数进行字母序排序。
  • 用with语句打开文件,无需手动关闭,避免文件资源泄漏。
  • 遍历排序后的列表,逐个判断每个字符串是否在指定范围内并实时输出,保证结果整体按字母顺序排列。
  • 最后添加print()确保输出结尾有换行符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 01:17:25