You need to enable JavaScript to run this app. Python3不借助itertools遍历列表拆分数字子列表的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

Python3不借助itertools遍历列表拆分数字子列表的实现方法

可替代的实现方案

下面给两种符合要求的实现,均不依赖itertools,逻辑清晰易读:


方案1:单次遍历直接生成最终结果

不需要额外拆分两次遍历,可以在遍历原列表的同时直接统计连续数字的长度,省去存储所有子列表的内存开销:

a_list = [1, 1, 'z', 1, 'x', 1, 1, 'c', 1, 1, 1, 'v', 1]
final_list = []
current_len = 0

for item in a_list:
    if isinstance(item, int):
        current_len += 1
    else:
        if current_len > 0:
            final_list.append(current_len)
        current_len = 0
# 处理遍历结束后剩余的连续数字
if current_len > 0:
    final_list.append(current_len)

print("final list is: ", final_list)
# 输出:[2, 1, 2, 3, 1]

如果需要保留中间的main_list也可以同步生成,代码调整很小。


方案2:while循环实现版本

你之前尝试失败的while写法可以参考如下实现:

a_list = [1, 1, 'z', 1, 'x', 1, 1, 'c', 1, 1, 1, 'v', 1]
main_list = []
index = 0
n = len(a_list)

while index < n:
    small_list = []
    # 连续收集数字
    while index < n and isinstance(a_list[index], int):
        small_list.append(a_list[index])
        index += 1
    main_list.append(small_list)
    # 跳过非数字元素
    while index < n and not isinstance(a_list[index], int):
        index += 1

print("main_list: ", main_list)
# 输出:[[1, 1], [1], [1, 1], [1, 1, 1], [1]]
# 要生成final_list直接推导即可
final_list = [len(sublist) for sublist in main_list]
print("final list is: ", final_list)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 23:30:00