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

Python获取列表奇数索引元素函数问题:为何返回结果不止[3]

问题排查与修复

你的代码只返回[3]的核心原因是while循环的条件逻辑错误:

  • 初始index=1,第一次循环满足index%2 !=0 and index < len(lst),添加元素后index变为2
  • 此时index%2 !=0不成立,整个条件为假,循环直接终止,无法继续遍历后续的奇数索引(3、5)

修复方案1:修正while循环逻辑

把循环条件改为仅判断索引是否在列表范围内,在循环内部判断当前索引是否为奇数:

def odd_indices(lst):
    odd_list = []
    index = 1
    while index < len(lst):
        if index % 2 != 0:
            odd_list.append(lst[index])
        index +=1
    return odd_list

print(odd_indices([4, 3, 7, 10, 11, -2]))  # 输出 [3, 10, -2]

修复方案2:用range直接遍历奇数索引(更简洁)

利用range(1, len(lst), 2)直接生成所有奇数索引,避免手动维护索引变量:

def odd_indices(lst):
    return [lst[index] for index in range(1, len(lst), 2)]

print(odd_indices([4, 3, 7, 10, 11, -2]))  # 输出 [3, 10, -2]

内容的提问来源于stack exchange,提问作者Amir.the.explorer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:10:15