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

数字字符串转字节列表函数的错误排查与修复求助

数字字符串转字节列表函数的错误排查与修复求助

我写了一个简单的函数,用来把仅由数字('0123456789')组成的字符串转换成字节列表。具体来说,它会找出最长的可能数字序列,要求这些序列转成整数后小于256。

举个例子,给定顺序的十进制数字,输出应该是 (0, 123, 45, 67, 89)。

我很快写出了下面这个函数:

from typing import List


DIGITS = {str(i): i for i in range(10)}

def get_bytes(s: str) -> List[int]:
    byte_list = []
    chunk = 0
    for c in f'{s}0':
        if (d := DIGITS.get(c)) is None:
            raise ValueError(f"{c} is not a digit")

        if (new := chunk * 10 + d) < 256:
            chunk = new
        else:
            byte_list.append(chunk)
            chunk = d

    return byte_list[not byte_list[0]:]

但测试的时候发现了问题,比如输入'0000'直接报错:

In [143]: get_bytes('0000')
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[143], line 1
----> 1 get_bytes('0000')

Cell In[142], line 14, in get_bytes(s)
     11         byte_list.append(chunk)
     12         chunk = d
---> 14 return byte_list[not byte_list[0]:]

IndexError: list index out of range

不过有些测试用例是正常的:

In [144]: get_bytes('100100100')
Out[144]: [100, 100, 100]

还有个测试用例的结果不符合预期:

In [145]: get_bytes('12301230123')
Out[145]: [123, 123, 123]

我自己尝试修复但没成功,现在还剩几个核心问题:

  • 输入'0000'时应该输出[0, 0, 0, 0],但现在直接报索引错误
  • 输入'12301230123'的正确输出应该是[123, 0, 123, 0, 123],但当前输出不对
  • 另外我有个硬性要求:''.join(str(i) for i in output) == original,也就是输出列表里的数字拼接后必须和原字符串完全一致

补充一下,我后来测试了最终接受的答案和正则表达式的实现,发现前者性能更好:

In [384]: get_bytes1(string) == get_bytes2(string)
Out[384]: True

In [385]: %timeit get_bytes1(string)
179 ms ± 588 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [386]: %timeit get_bytes2(string)
161 ms ± 748 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [387]: len(string)
Out[387]: 1000001

这里get_bytes2是接受的答案的实现,get_bytes1是正则方案,测试用的string是圆周率的前1000000位小数前面加了一个'3'。

备注:内容来源于stack exchange,提问作者Ξένη Γήινος

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:00:28