"""unzip simple list-like obj
"""
def unzip(p, n):
""" Example:
>>> unzip(['a','b','c','d','e'], 3)
[('a', 'd'), ('b', 'e'), ('c', None)]
"""
mlen, lft = divmod(len(p), n)
if lft != 0: mlen += 1
lst = [[None]*mlen for i in range(n)]
for i in range(len(p)):
j, k = divmod(i, n)
lst[k][j] = p[i]
return map(tuple, lst)
print unzip(['a','b','c','d','e'], 3)
##########################################
the output is:
>>>
[('a', 'd'), ('b', 'e'), ('c', None)]
>>>
本文介绍了一个简单的 Python 函数,该函数能够将一个列表拆分成指定数量的子列表,并确保每个子列表尽可能等长。如果原始列表不能被平均分割,额外的元素会依次分配到每个子列表中,最后一个子列表可能会包含 None 值来填充。
1100

被折叠的 条评论
为什么被折叠?



