Python while循环遍历子列表提前终止 仅输出前2个元素问题
问题排查与修复
错误原因
- while循环末尾存在无条件
break语句,第一次循环执行完成后会直接跳出循环,因此仅能打印前2个元素,这是核心问题。 - 外层for循环迭代范围写为
range(0,5),但populated_indices仅包含3个元素,当index≥3时会触发列表索引越界异常。 - while循环终止条件
k <= len(lst_separated[populated_indices[index]])/2逻辑不合理,对于长度为偶数的列表,迭代次数应为列表长度整除2,k从0开始计数时应使用k < len(xxx)//2作为终止条件,避免多执行一次循环触发索引越界。
修复后可运行代码
outcome = [] lst_separated = [['1605', '1607'],[],['20425', '20427','205425', '202427']] populated_indices = [0,1,2] for index in range(len(populated_indices)): i = 0 j = 1 k = 0 current_lst = lst_separated[populated_indices[index]] # 空列表直接跳过处理 if not current_lst: continue # 迭代次数为列表长度整除2 while k < len(current_lst) // 2: pos1 = int(current_lst[i]) pos2 = int(current_lst[j]) i += 2 j += 2 k += 1 # 同时保存对应populated_indices值到outcome outcome.append((populated_indices[index], pos1, pos2)) print(populated_indices[index], pos1, pos2)
运行输出
0 1605 1607 2 20425 20427 2 205425 202427
内容的提问来源于stack exchange,提问作者user17153595
相关产品推荐
相关产品推荐

