Last active
March 11, 2019 07:41
-
-
Save Elfsong/4b88c2c688bc9b8db77f6473c08bfcef to your computer and use it in GitHub Desktop.
优雅地均匀分割字符串
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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