Skip to content

Instantly share code, notes, and snippets.

@Elfsong Elfsong/average_split.py
Last active Mar 11, 2019

Embed
What would you like to do?
优雅地均匀分割字符串
def avsplit1(s, n):
fn = len(s)//n
rn = len(s)%n
ar = [fn+1]*rn+ [fn]*(n-rn)
si = [i*(fn+1) if i<rn else (rn*(fn+1)+(i-rn)*fn) for i in range(n)]
sr = [s[si[i]:si[i]+ar[i]] for i in range(n)]
return sr
def avsplit2(s, n):
fn = len(s)//n
rn = len(s)%n
sr = []
ix = 0
for i in range(n):
if i<rn:
sr.append(s[ix:ix+fn+1])
ix += fn+1
else:
sr.append(s[ix:ix+fn])
ix += fn
return sr
print avsplit1(s,n)
print avsplit2(s,n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.