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

如何统计数组中的特殊字符、普通字符并计算数组内数字总和?

问题与解决方案

原问题

现有如下Python代码:

ar=input("Enter the elements:").split()
sum=0
cr=0

for i in range(len(ar)):
    if(not ar[i].isalpha()):
        a=int(ar[i])
        sum=sum+a
    else:
         cr=cr+1
print("Sum of the elements is :",sum)
print(" No of Characters in the array:",cr)

当前代码仅能统计数组中的普通字符,无法统计特殊字符,现需实现统计数组中的特殊字符、普通字符,并计算数组内数字总和的功能,请问该如何修改代码?

修改后的代码

ar = input("Enter the elements:").split()
total_sum = 0
alpha_count = 0
special_char_count = 0

for elem in ar:
    # 判断是否为纯数字元素
    if elem.isdigit():
        total_sum += int(elem)
    # 判断是否为纯字母元素
    elif elem.isalpha():
        alpha_count += 1
    # 既非数字也非字母的归为特殊字符
    else:
        special_char_count += 1

print(f"Sum of the numeric elements: {total_sum}")
print(f"Number of alphabetic characters: {alpha_count}")
print(f"Number of special characters: {special_char_count}")

修改说明

  • 变量语义优化:将原代码中模糊的sum改为total_sum(避免与Python内置函数sum重名),cr改为alpha_count,新增special_char_count专门统计特殊字符数量,代码可读性更强。
  • 遍历逻辑简化:直接遍历数组元素而非通过索引,代码更简洁直观。
  • 判断逻辑分层:
    1. 优先用isdigit()判断元素是否为纯数字,符合则累加到总和;
    2. 再用isalpha()判断是否为纯字母,符合则统计字母数量;
    3. 剩余既非数字也非字母的元素(如!、@、_等)统一归为特殊字符,统计其数量。
  • 输出格式优化:使用f-string格式化输出,内容更清晰易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:00:59