Python列表奇偶筛选代码执行卡顿问题求助
问题排查与修复方案
核心问题:死循环导致卡顿
你的odd和even函数里错误使用了while循环而非if判断。比如遇到奇数时,while(lst[i]%2!=0)的条件会永远成立(元素本身是奇数,不会发生变化),程序会无限次将该元素添加到结果列表,进入死循环,直接导致卡顿。
其他可优化点
- 导入的
from os import lstat完全未使用,可删除 - 函数依赖全局变量
n,灵活性不足,建议改用len(lst)遍历列表 - 无需提前创建空列表传入函数,直接在函数内部生成结果列表更简洁
修复后的代码
def get_odd(lst): oddlst = [] for num in lst: if num % 2 != 0: oddlst.append(num) return oddlst def get_even(lst): evenlst = [] for num in lst: if num % 2 == 0: evenlst.append(num) return evenlst lst = [] n = int(input("enter number of elements \n")) print("\nenter the elements \n") for i in range(0, n): num = int(input()) lst.append(num) print(lst) choice = input(" Do you want to print odd elements or even elements \n (odd/even) \n") if choice == "odd": print(get_odd(lst)) elif choice == "even": print(get_even(lst)) else: print("invalid choice")
代码说明
- 将
while替换为if,彻底解决死循环问题 - 函数内部创建结果列表,无需外部传入,逻辑更清晰
- 直接用
for num in lst遍历列表,比索引遍历更直观 - 删除无用的
lstat导入
内容的提问来源于stack exchange,提问作者Muhammed
相关产品推荐
相关产品推荐

