python – 在几乎相等的部分和返回边界中拆分列表
发布时间:2020-12-20 11:04:07 所属栏目:Python 来源:网络整理
导读:我想拆分列表并返回边界,因此在扩展中不应该存在单个元素. 例如 split(list(range(1,101)),2) # should return [[1,50],[51,100]]split(list(range(1,3)# should return[[1,33],[34,66],[67,6)),2],[3,5]] # Ideally last element should merge with last if
我想拆分列表并返回边界,因此在扩展中不应该存在单个元素.
例如 split(list(range(1,101)),2) # should return [[1,50],[51,100]] split(list(range(1,3) # should return [[1,33],[34,66],[67,6)),2],[3,5]] # Ideally last element should merge with last if last one has no pair. 到目前为止我试过了 def split(l,n): x = list(range(1,l+1)) return [x[i:i+n] for i in range(0,len(x),int(len(x)/n))] print(split(20,2)) 返回[[1,[11,12]]而不是[[1,10],20]] 解决方法def csplit(m,n): div_ = m//n step = div_ if div_ > 1 else 2 # determine step for range function (at least 2 'alternate steps') lis = [] for i in range(1,m+1,step): if (m-(i+max(1,div_-1))) > 1: # append list only if remains at least two elements remains lis.append([i,i+max(1,div_-1)]) else: if not m == i: # in case if m and i not equal and not more then one element left then construct list which include that element lis.append([i,m]) break # break the loop from iterating any further return lis if __name__ == "__main__": print(csplit(100,2)) print(csplit(100,3)) print(csplit(5,3)) 输出: [[1,100]] [[1,5]] 同一个衬垫: def csplit(m,n): return [[i,m//n-1)] if (m-(i+max(1,m//n-1))) > 1 else [i,m] for i in range(1,max(m//n,2)) if not i==m] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |