我有一大組資料,我正在使用glob.glob(some_file_path.dat)python將這些資料從我的桌面匯入 jupyter 。這將輸出一個包含每個資料檔案路徑的單個串列作為字串(總共 1851 個)。我希望做的是將這個龐大的串列分成 10 個文本檔案(因此 9 個檔案將包含 185 個字串,1 個將包含 186 個,因為總共有 1851 個)。我有點不知所措,所以他們通過指定 10 個文本檔案(每個檔案的名稱不同)作為要拆分的數字來“均勻地”拆分。
任何幫助將不勝感激。
uj5u.com熱心網友回復:
我發現之前已經回答過這個問題:如何將串列分成大小均勻的塊?
不同之處在于您似乎想要拆分它,以便塊具有共享的最小大小(在您的示例中為 185)。使用共享的最大大小拆分串列更容易。那將是九個大小為 186 的串列和一個大小為 177 的串列。
這是一種按照您的描述拆分串列的方法。你可以用更少的行來完成,但我想更清楚地展示這個程序:
import math
from pathlib import Path
list_with_1851_strings = ['path'] * 1851
steps = 10
step_size = math.floor(len(list_with_1851_strings) / steps)
# or just do integer division: len(list_with_1851_strings) // steps
for n in range(steps):
start = n * step_size
if len(list_with_1851_strings[start:]) > (step_size * 2):
end = start step_size
else:
// If end is None in a slice, the sub list will go to the end
end = None
sub_list = list_with_1851_strings[start:end]
# Write list to disk
sub_list_file = Path(f'sublist_{n}.txt')
sub_list_file.write_text('\n'.join(sub_list))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/346729.html
下一篇:如何使用Encoding.ASCII.GetBytes處理大量資料?(拋出OutOfMemoryException)
