Python:将列表拆分为定义大小的块并填充休息

han*_*ast 4 python

我想将列表拆分为具有相同列数的行,我正在寻找最佳(最优雅/ pythonic)方式来实现此目的:

>>> split.split_size([1,2,3], 5, 0)
[[1, 2, 3, 0, 0]]

>>> split.split_size([1,2,3,4,5], 5, 0)
[[1, 2, 3, 4, 5]]

>>> split.split_size([1,2,3,4,5,6], 5, 0)
[[1, 2, 3, 4, 5], [6, 0, 0, 0, 0]]

>>> split.split_size([1,2,3,4,5,6,7], 5, 0)
[[1, 2, 3, 4, 5], [6, 7, 0, 0, 0]]
Run Code Online (Sandbox Code Playgroud)

这就是我到目前为止所提出的:

def split_size(l, size, fillup):
    """
    splits list into chunks of defined size, fills up last chunk with fillup if below size
    """
    # len(l) % size or size
    # does i.e. size=5: 3->2, 4->1, 5->0
    stack = l + [fillup] * (size - (len(l) % size or size))
    result = []
    while len(stack) > 0:
        result.append(stack[:5])
        del stack[:5]
    return result
Run Code Online (Sandbox Code Playgroud)

我敢肯定必须有一些更聪明的解决方案.特别是对于"逆mod"部分:len(l)%大小或大小必须有一个更易读的方法来做到这一点,不是吗?

Mar*_*ers 6

itertools配方叫石斑鱼你想要做什么:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
Run Code Online (Sandbox Code Playgroud)