Python课程作业求助:列表推导式实现非元音字母过滤失败
问题分析与解决方案
你的代码报错的核心原因是未定义vowels变量,程序不知道哪些字母属于元音,所以会抛出NameError。
修正后的代码
先定义元音集合(用集合做成员查询效率更高),再执行列表推导逻辑:
word = input() vowels = {'a', 'e', 'o', 'u'} # 明确定义元音字母集合 out = [l for l in word if l not in vowels] print(out)
可选优化(兼容大小写)
如果需要处理输入中的大写元音(比如输入"Orange"时过滤掉'O'),可以扩展元音集合,或者统一将字符转小写后判断:
word = input() # 方式1:包含大小写元音 vowels = {'a', 'e', 'o', 'u', 'A', 'E', 'O', 'U'} out = [l for l in word if l not in vowels] # 方式2:转小写判断,保留原字符格式 out = [l for l in word if l.lower() not in {'a', 'e', 'o', 'u'}] print(out)
内容的提问来源于stack exchange,提问作者ΧΡΙΣΤΟΣ A
相关产品推荐
相关产品推荐

