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

Python报错String indices must be integers,求列表字符统计解法

问题分析与解决

报错原因

string indices must be integers错误的核心是:你试图用字符作为索引访问字符串元素,但字符串仅支持整数索引。比如写item['C']是完全无效的,因为字符串索引必须是数字(如item[0]取第一个字符)。

大概率是你的循环逻辑出错——内层循环遍历的是字符串里的单个字符,却把这个字符当成整数索引去使用,才触发了报错。

正确实现方式

要统计列表bins中每个字符串元素里'C'的数量,有两种实用的实现方式:

方式1:用字符串自带的count()方法(最简便)

直接遍历bins中的每个字符串,调用count('C')获取该字符串内'C'的出现次数,再将结果收集到列表中:

# 假设你的bins是类似这样的字符串列表
bins = ["ACB", "DCE", "FCG", "HIJ"]
c_counter = [s.count('C') for s in bins]
print(c_counter)  # 输出:[1, 1, 1, 0]

方式2:手动循环统计(适合理解底层逻辑)

如果想手动实现计数,内层循环直接遍历字符串的每个字符,判断是否为'C'即可,无需使用索引:

bins = ["ACB", "DCE", "FCG", "HIJ"]
c_counter = []
for s in bins:
    cnt = 0
    for char in s:
        if char == 'C':
            cnt += 1
    c_counter.append(cnt)

错误代码修正示例

如果你之前的代码是类似下面的错误写法:

# 错误示例,请勿使用
bins = ["ACB", "DCE", "FCG", "HIJ"]
c_counter = []
for item in bins:
    count = 0
    for i in item:  # 这里i是字符串里的单个字符,比如'A'、'C'
        if item[i] == "C":  # 用字符i作为索引,触发报错
            count +=1
    c_counter.append(count)

只需要把内层循环逻辑改成直接判断字符即可,不需要item[i],直接用i == 'C':

# 修正后的代码
bins = ["ACB", "DCE", "FCG", "HIJ"]
c_counter = []
for item in bins:
    count = 0
    for char in item:
        if char == "C":
            count +=1
    c_counter.append(count)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:01:21