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

如何在Python列表中查找数值6的每第三个实例的索引

实现查找每第三个6的索引

嗨,其实这个需求根本不需要嵌套循环,单趟遍历就能轻松搞定!核心思路就是一边遍历列表,一边统计遇到的6的数量,每当计数刚好是3的倍数(也就是第3、6、9……个6)时,就把当前的索引记录下来。

具体实现代码

这里直接给出针对你需求的函数:

def six_finder(lst):
    six_count = 0
    result_indices = []
    # 用enumerate同时获取索引和对应元素
    for index, num in enumerate(lst):
        if num == 6:
            six_count += 1
            # 检查是否是第3、6、9...个6
            if six_count % 3 == 0:
                result_indices.append(index)
    return result_indices

代码解释

  • enumerate(lst):这个函数能帮我们在遍历列表时,同时拿到每个元素的索引和数值,比用range(len(lst))再取元素的写法更简洁直观。
  • six_count:用来累计已经遇到的6的数量,每碰到一个6就加1。
  • 每次碰到6后,判断six_count是否是3的倍数——如果是,说明这是我们要找的「每第三个6」,把它的索引加入结果列表。

测试示例

用你给出的列表测试一下:

l = [5, 2, 2, 1, 4, 5, 4, 6, 6, 5, 5, 3, 3, 2, 1, 3, 5, 3, 5, 2, 4, 4, 2, 3, 3, 2, 6, 2, 3, 6, 3, 6, 1, 6]
print(six_finder(l))  # 输出: [26, 33]

扩展通用版本

如果以后你需要找「每第N个某个目标值」的索引,可以把函数改成通用版:

def nth_target_finder(lst, target, n):
    target_count = 0
    result_indices = []
    for index, num in enumerate(lst):
        if num == target:
            target_count += 1
            if target_count % n == 0:
                result_indices.append(index)
    return result_indices

# 调用示例:找列表l中每第3个6的索引
print(nth_target_finder(l, 6, 3))  # 同样输出: [26, 33]

这样不管是找每第2个5,还是每第4个2,都能直接用这个函数啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:15:12