如何将列表中相邻差值不为1的元素拆分到多个独立子列表中
数字列表按连续步长1拆分结果及实现
拆分结果
- list1 = [29]
- list2 = [64, 65, 66]
- list3 = [128, 129, 130]
- list4 = [166, 167, 168]
- list5 = [184, 185, 186]
- list6 = [215, 216, 217]
- list7 = [237, 238, 239]
- list8 = [349, 350, 351]
- list9 = [443]
- list10 = [483, 484, 485]
- list11 = [495, 496, 497]
- list12 = [526, 527, 528]
- list13 = [542, 543, 544]
- list14 = [564, 565, 566]
Python实现代码
def split_continuous_lists(nums): if not nums: return [] # 初始化结果列表,存入第一个元素作为首个子列表的起始 result = [[nums[0]]] for num in nums[1:]: # 当前元素和上一个子列表的末尾元素差值为1则追加,否则新建子列表 if num - result[-1][-1] == 1: result[-1].append(num) else: result.append([num]) return result # 输入待拆分的数字列表 input_nums = [29, 64, 65, 66, 128, 129, 130, 166, 167, 168, 184, 185, 186, 215, 216, 217, 237, 238, 239, 349, 350, 351, 443, 483, 484, 485, 495, 496, 497, 526, 527, 528, 542, 543, 544, 564, 565, 566] output = split_continuous_lists(input_nums) # 格式化打印结果 for index, sub_list in enumerate(output, 1): print(f"list{index}={sub_list}")
内容的提问来源于stack exchange,提问作者It Engineer
相关产品推荐
相关产品推荐

