将 python 列表约n等分(大多数情况下是无法分的正好的,除非 n % ncut==0)
自己懒得写,google了半天,大多数不是有错就是从有错的地方抄来的,血压拉满。于是自己写了两种,时间复杂度均为O(n)
如果有更好的办法或者有错误可以分享并指正。
顺便吐槽一句python的数据结构实现真的是太令人头疼了。
def partition_size(ls: list, size):
"""
Returns a new list with elements
of which is a list of certain size.
>>> partition_size([1, 2, 3, 4], 3)
[[1, 2, 3], [4]]
:param ls:
:param size:
:return: list cut by size
"""
if size <= 0:
return ls
return [ls[i:i + size] for i in range(0, len(ls), size)]
def partition_cut(ls: list, ncut):
"""
Returns a new list with elements
of which is a list of certain size.
>>> partition_cut([1, 2, 3, 4, 5], 3)
[[1, 2], [3, 4], [5]]
:param ls:
:para