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

如何编写Python列表处理函数返回递增的位范围结果

问题描述

需要编写函数按[from:to]格式返回连续位段的起止范围,输出逐次递增的位范围,初始实现代码如下:

cntlist = [5,1,4,3,1]
def find_size(cnt):
    if cnt>1:
        a = "[%s:%s]" % (cnt-1, cnt-cnt)
        left = cnt-1
        right = cnt-cnt
    if cnt==1:
        a = "[%s]" % (cnt)
        left = a
        right = a
    return a, left, right

newlist = list(map(find_size, cntlist))
print(newlist)

当前代码运行输出:

[('[4:0]', 4, 0), ('[1]', '[1]', '[1]'), ('[3:0]', 3, 0), ('[2:0]', 2, 0), ('[1]', '[1]', '[1]')]

期望输出:

['[4:0]', '[5]', '[9:6]', '[12:10]', '[13]']

匹配规则:

  • 所有位段是连续累计的,后一个段的起始位置紧接前一个段的结束位置
  • 若cntlist中的元素值为1,对应范围仅包含单个位,取值为前一个范围的左边界数值加1
  • 若元素值大于1,范围格式为[高位:低位],段内位的数量等于元素值
错误原因

原实现用map单独传入每个计数值计算,函数内部无法获取之前位段的边界累计值,每个段都独立从0开始计算,自然无法得到连续递增的全局位范围。这个场景不需要递归,遍历列表时维护一个当前已分配到的最高位偏移量即可。

正确实现
cntlist = [5,1,4,3,1]

def get_bit_ranges(cnt_list):
    ranges = []
    prev_high = -1  # 初始已分配最高位为-1,第一个段从0开始
    for cnt in cnt_list:
        current_low = prev_high + 1
        if cnt == 1:
            ranges.append(f"[{current_low}]")
            prev_high = current_low
        else:
            current_high = current_low + cnt - 1
            ranges.append(f"[{current_high}:{current_low}]")
            prev_high = current_high
    return ranges

print(get_bit_ranges(cntlist))

运行代码输出完全符合预期:

['[4:0]', '[5]', '[9:6]', '[12:10]', '[13]']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 06:12:40