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

Python列表推导式实现非元音非标点字符统计报错解决

解决UnboundLocalError并实现非元音非标点字符统计

你的错误源于列表推导式逻辑混乱:错误嵌套了不必要的循环,导致punctuation变量在未定义时被引用,触发UnboundLocalError。

核心问题

原代码里的and punctuation for punctuation in stri if punctuation not in punctuations是完全错误的逻辑——你不需要嵌套循环,只需要对每个字符同时做两个条件判断即可。

正确代码实现

# 元音集合(用集合查询效率优于列表)
vowels = {'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'}
# 标点字符串(也可转成集合提升效率)
punctuations = '''!()-[]{};:'",<>./?@#$%^&*_~'''

input_str = input("Enter a string: ")
# 列表推导式筛选符合条件的字符,再取长度
count = len([char for char in input_str if char not in vowels and char not in punctuations])
print("Count:", count)

验证示例

输入:

Enter a string: Coding!

输出:

Count: 4

(统计的是c、d、n、g四个字符,o、i是元音,!是标点,均被排除)

优化小技巧

将punctuations也转为集合,能大幅提升成员查询的速度,尤其是处理长文本时:

punctuations = set('''!()-[]{};:'",<>./?@#$%^&*_~''')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 10:40:36