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

Python:从降序列表中提取连续整数的高位额外元素

问题描述

现有两个降序列表:

list1 = [81, 68, 53, 28, 19, 7, 2, 0]

list1中无连续整数(相邻两数差值不为1),无需处理。

list2 = [68, 67, 53, 21, 20, 19, 9, 7, 1, 0]

list2存在多组连续整数:(68,67)、(21,20,19)、(1,0)。需求是生成新列表numbs_list,存储每组连续整数中除最低位外的所有高位元素,最终预期numbs_list为[68,21,20,1]。

以下是未达成目标的代码:

####################################################
list2 = [68, 67, 53, 21, 20, 19, 9, 7, 1, 0]
numbs_list= []
complete = False
i = 0
# start = 0
# end = len(list2) -1
while complete is False:
    if len(list2) > 1:
        # if index 1 is next-in-line to index 0
        # if 67 == 67(68 -1)
        if list2[i +1] == list2[i] -1:

            # add 68 to numbs list
            numbs_list.append(list2[i])

            # remove 68 from list2
            list2.pop(list2.index(list2[i]))
        else:
            list2.pop(list2.index(list2[i]))
    else:
        complete = True

    # start += 1
    # if start == end:
    #     complete = True

# from list2 this is what i need numbs_list to have stored once the while loop is done:
numbs_list = [68, 21, 20, 1]
# whats left in list2 does not matter after the numbs_list is finalised as list2 will eventually get cleared and repopulated.
####################################################

注:“next-in-line”指连续整数,即相邻数差值为1,例如(1,0)、(11,10,9)等。

问题分析与修正

原代码逻辑存在两处核心问题:

  1. 循环中通过list2.pop(list2.index(list2[i]))删除元素,每次删除后列表长度变化,但i未同步更新,导致遍历逻辑混乱,无法正确处理多元素连续序列。
  2. 处理连续序列时仅添加当前元素就删除,无法捕获像21,20,19这类多元素连续组里的所有高位元素。

由于已知列表始终为降序排列,可以直接遍历列表,通过判断相邻元素差值是否为1来收集目标元素,无需修改原列表(原列表后续会被清空,无需保留)。

修正后的代码:

list2 = [68, 67, 53, 21, 20, 19, 9, 7, 1, 0]
numbs_list = []

# 遍历至倒数第二个元素,避免索引越界
for i in range(len(list2) - 1):
    current = list2[i]
    next_num = list2[i+1]
    # 降序下,当前元素与下一个元素差值为1即为连续整数
    if current - next_num == 1:
        numbs_list.append(current)

print(numbs_list)  # 输出: [68, 21, 20, 1]

代码说明

  • 利用降序特性,通过current - next_num == 1直接判断两数是否连续,逻辑简洁准确。
  • 遍历过程中,只要当前元素与下一个元素连续,就将当前元素加入结果列表,自然收集到每组连续序列中除最低位外的所有高位元素。
  • 无需修改原列表,执行效率更高,逻辑更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:09:26