試試這個方法:
>>> s
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> n
5
>>> [int(''.join(str(x) for x in s[i*n: i*n + n])) for i in range(len(s)/n)]
[12345, 678910, 1112131415]
只是一個建議尚未完全測試的代碼
編輯:在文件中寫不喜歡:
>>> L = [''.join(str(x) for x in s[i*n: i*n + n]) for i in range(len(s)/n)]
>>> with open("file", 'w') as f:
... for v in L:
... f.write(v + ', ')
...
我還沒有投給int當我在一個文件中寫入。
更新時間:提高代碼
對於損失少拆,你可以做吊頂師任意長度的列表。我提高了代碼,並添加下面:
def split_list(L, n):
"""split successive n-sized groups from L as a list
"""
from math import ceil
parts = int(ceil(len(L)/float(n))) # ceilng division 5/2 ==> 3
return [int(''.join(str(_) for _ in L[i*n: i*n + n])) for i in range(parts)]
一些測試案例
# test cases
n = 5
s = [1, 2, 3 ]
print split_list(s, 5) # output [123]
s = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print split_list(s, 5) # output [12345, 678910, 111213]
s = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
print split_list(s, 5) # output [12345, 678910, 1112131415]
嘗試檢查: http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-均勻大小的塊在python –