将数字列表压缩或编码为单个字母数字字符串的最佳方法是什么?

pup*_*eno 8 string algorithm encoding

将任意长度和大小的数字列表压缩或编码为单个字母数字字符串的最佳方法是什么?

目标是能够将1,5,8,3,20,212,42之类的内容转换为类似a8D1jN的内容,以便在URL中使用,然后返回到1,5,8,3,20,212,42.

对于结果字符串,我可以使用任何数字和任何ascii字符,小写和大写,所以:0-9a-zA-Z.我不想有任何标点符号.

更新:添加了关于哪些字符没问题的说明.

AHM*_*AHM 5

如果您将列表视为字符串,则您需要编码11个不同的字符(0-9和逗号).这可以用4位表示.如果您愿意添加,请说$和!在你的可接受字符列表中,你将有64个不同的输出字符,因此每个字符可以编码6位.

这意味着您可以将字符串映射到编码的字符串,该字符串比原始字符串短约30%,并且相当模糊和随机查看.

这样您就可以将数字序列[1,5,8,3,20,212,42]转码为字符串"gLQfoIcIeQqq".

更新:我感到很有灵感并为此解决方案编写了一个python解决方案(不是很快但功能足够......)

ZERO = ord('0')
OUTPUT_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$!"

def encode(numberlist):

    # convert to string -> '1,5,8,3,20,212,42'
    s = str(numberlist).replace(' ','')[1:-1]

    # convert to four bit values -> ['0010', '1011', '0110', ... ]
    # (add 1 to avoid the '0000' series used for padding later)
    four_bit_ints = [0 <= (ord(ch) - ZERO) <= 9 and (ord(ch) - ZERO) + 1 or 11 for ch in s]
    four_bits = [bin(x).lstrip('-0b').zfill(4) for x in four_bit_ints]

    # make binary string and pad with 0 to align to 6 -> '00101011011010111001101101...'
    bin_str = "".join(four_bits)
    bin_str = bin_str + '0' * (6 - len(bin_str) % 6)

    # split to 6bit blocks and map those to ints
    six_bits = [bin_str[x * 6 : x * 6 + 6] for x in range(0, len(bin_str) / 6)]
    six_bit_ints = [int(x, 2) for x in six_bits]

    # map the 6bit integers to characters
    output = "".join([OUTPUT_CHARACTERS[x] for x in six_bit_ints])

    return output

def decode(input_str):

    # map the input string from characters to 6bit integers, and convert those to bitstrings
    six_bit_ints = [OUTPUT_CHARACTERS.index(x) for x in input_str]
    six_bits = [bin(x).lstrip('-0b').zfill(6) for x in six_bit_ints]

    # join to a single binarystring
    bin_str = "".join(six_bits)

    # split to four bits groups, and convert those to integers
    four_bits = [bin_str[x * 4 : x * 4 + 4] for x in range(0, len(bin_str) / 4)]
    four_bit_ints = [int(x, 2) for x in four_bits]

    # filter out 0 values (padding)
    four_bit_ints = [x for x in four_bit_ints if x > 0]

    # convert back to the original characters -> '1',',','5',',','8',',','3',',','2','0',',','2','1','2',',','4','2'
    chars = [x < 11 and str(x - 1) or ',' for x in four_bit_ints]

    # join, split on ',' convert to int
    output = [int(x) for x in "".join(chars).split(',') if x]

    return output


if __name__ == "__main__":

    # test
    for i in range(100):
        numbers = range(i)
        out = decode(encode(numbers))
        assert out == numbers

    # test with original series
    numbers = [1,5,8,3,20,212,42]
    encoded = encode(numbers)
    print encoded         # prints 'k2UBsZgZi7uW'
    print decode(encoded) # prints [1, 5, 8, 3, 20, 212, 42]
Run Code Online (Sandbox Code Playgroud)


dou*_*gvk 1

取决于数字的范围——在合理的范围内,简单的字典压缩方案可以工作。

考虑到您对 10k 行的编辑和估计,每个数字映射到 [A-Za-z0-9] 的三元组的字典方案对于 62*62*62 不同的条目来说可能是唯一的。