我想将我的列表拆分为具有相同列数的行,我正在寻找实现这一点的最佳(最优雅/最具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]]
到目前为止我就是这么想的:
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
长度(l)%大小或大小
必须
用一种更具可读性的方式来做这件事,不是吗?