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

Python相同字符分组到子列表时最后一个字符被忽略的问题求助

相同字符分组子列表的代码修复

问题根源

  1. 外层循环条件i < len(test) - 1直接排除了最后一个索引(10),导致最后一个字符无法进入处理流程
  2. 内层循环条件test[i] == test[j] and j < len(test) - 1存在两个问题:
    • 先判断字符相等再判断索引范围,当j等于len(test)时会触发索引越界
    • j < len(test)-1的限制让j无法遍历到最后一个索引,即使最后一个字符和当前组字符相同也不会被加入

修复后的代码

test = 'abccdeeefgg'
ml = []
i = 0

while i < len(test):
    elem = [test[i]]
    j = i + 1
    # 先判断索引合法性,再比较字符,避免越界;取消len(test)-1的限制
    while j < len(test) and test[i] == test[j]:
        elem.append(test[j])
        i = j
        j += 1
    ml.append(elem)
    i += 1

print(ml)

修复说明

  • 外层循环改为i < len(test),确保所有索引(包括最后一个)都能被处理
  • 内层循环调整条件顺序,先检查j < len(test)再比较字符,彻底避免索引越界问题
  • 移除内层循环中len(test)-1的限制,让j可以遍历到字符串最后一位,保证相同字符都能被归入同一子列表

运行输出:

[['a'], ['b'], ['c', 'c'], ['d'], ['e', 'e', 'e'], ['f'], ['g', 'g']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:01:14