Skip to content

Instantly share code, notes, and snippets.

@Elfsong
Last active March 11, 2019 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Elfsong/4b88c2c688bc9b8db77f6473c08bfcef to your computer and use it in GitHub Desktop.
Save Elfsong/4b88c2c688bc9b8db77f6473c08bfcef to your computer and use it in GitHub Desktop.
优雅地均匀分割字符串
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