如何在Python 3.5中将整数拆分为n长度列表?

时间:2016-08-25 04:43:51

标签: python python-3.x

我需要能够将一个整数分成均匀的n长度列表。

例如n = 4,

12 -> [0, 0, 1, 2]
1234 -> [1, 2, 3, 4]
12345 -> [1, 2, 3, 45]
123456 -> [1, 2, 34, 56]
1234567 -> [1, 23, 45, 67]
12345678 -> 12, 34, 56, 78]
123456789 -> [12, 34, 56, 789]

我确信我已经过多了我给出的例子,但这有助于明确这一点。

我过去用于将项目拆分为列表的代码是:

def split(s, chunk_size):
    a = zip(*[s[i::chunk_size] for i in range(chunk_size)])
    return [''.join(t) for t in a]

但是这段代码只会分成n个块。 (来自StackOverflow的代码,我不记得确切的帖子,抱歉)。

感谢您的帮助。

4 个答案:

答案 0 :(得分:4)

def split(seq, n):
    """Partitions `seq` into `n` successive slices of roughly equal size.

    The sizes of each yielded slice shall differ by at most one.
    """
    q, r = divmod(len(seq), n)
    start = 0

    for i in range(n):
        size = q + (i < r)
        yield seq[start : start + size]
        start += size

它基本上与this popular answer的工作方式相同,只是它将余数均匀地分配到每个 n 切片中。

不幸的是,这将分配到列表的头部。要根据您的情况进行调整,您需要将size = q + (i < r)更改为:

size = q + (i >= (n - r))

通过此更改,以下内容:

print(list(split('1234', 4)))
print(list(split('12345', 4)))
print(list(split('123456', 4)))
print(list(split('1234567', 4)))
print(list(split('12345678', 4)))
print(list(split('123456789', 4)))

打印:

['1', '2', '3', '4']
['1', '2', '3', '45']
['1', '2', '34', '56']
['1', '23', '45', '67']
['12', '34', '56', '78']
['12', '34', '56', '789']

答案 1 :(得分:1)

Ahsan答案的变体应该正确分配到序列末尾的余数:

from itertools import accumulate

def split(s, parts):
    s = str(s)
    r, rem = divmod(len(s), parts)
    norem = parts - rem
    counts = [r]*norem + [r+1]*rem
    # Prepend 0 to counts only for accumulate to start from 0
    return [s[start:start+cnt] for start, cnt in zip(accumulate([0] + counts), counts)]

答案 2 :(得分:0)

选择的答案有其优点,但我是以更直接的方式做到的:

def chunk(s, n):
    return [s[i:i+n] for i in range(0, len(s), n)]

def split(s0, numberOfChunks):
    s = ('0' * max(0, numberOfChunks - len(s0))) + s0
    sizeOfChunk = len(s) / numberOfChunks
    numberOfSmallChunks = numberOfChunks - len(s) % numberOfChunks
    return chunk(s[:numberOfSmallChunks * sizeOfChunk], sizeOfChunk) +
           chunk(s[sizeOfChunk*numberOfSmallChunks:], sizeOfChunk+1)

答案 3 :(得分:-1)

抱歉 - 代码有问题 它正在根据规范

工作
def split(s, list_size):
    s = str(s)
    assert len(s) >= list_size, "assertion failed"
    r, rem = divmod(len(s), list_size)
    lst = []
    for i in range(list_size):
        lst.append(s[i*r:(i+1)*r])
    for j in range(rem):
        lst[-(j+1)] += s[list_size + j]
    return lst