Python列表元素分组统计:遇指定字符串重置计数的实现求助
解决方案
实现思路
通过一次遍历列表,维护当前累计的"small item"计数,遇到"large item"时记录当前计数并追加0,同时重置计数;遍历结束后记录最后一段的累计计数,即可得到目标结果。
Python 代码实现
items = ['small item', 'small item', 'large item', 'small item', 'small item'] current_count = 0 result = [] for item in items: if item == 'small item': current_count += 1 elif item == 'large item': result.append(current_count) result.append(0) current_count = 0 # 处理遍历结束后剩余的计数 result.append(current_count) print(result) # 输出: [2, 0, 2]
代码说明
current_count:用于跟踪当前连续出现的"small item"数量- 遇到"large item"时,先将之前累计的
current_count加入结果列表,再追加0(对应该"large item"的统计值),随后重置计数 - 遍历完成后必须追加最后一段的累计计数,因为最后一段没有触发"large item"的处理逻辑
内容的提问来源于stack exchange,提问作者CanB
相关产品推荐
相关产品推荐

