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
相关产品推荐
相关产品推荐

