如何将包含字符串的大列表拆分为多个文本文件
How do I split a large list containing strings into multiple text files
我有一大组数据,我正在使用 glob.glob(some_file_path.dat)
从我的桌面导入到 jupyter 到 python。这将输出一个列表,其中包含每个数据文件路径作为字符串(总共 1851 个)。我想做的是将这个庞大的列表分成 10 个文本文件(因此 9 个文件将包含 185 个字符串,而 1 个将包含 186 个,因为总共有 1851 个)。我有点不知所措,所以他们根据 'evenly' 进行拆分,指定 10 个文本文件(每个文件的名称不同)作为要拆分的数量。
如有任何帮助,我们将不胜感激。
我发现这个问题之前已经回答过:How do you split a list into evenly sized chunks?
不同之处在于您似乎想要拆分它以便块具有共享的最小大小(在您的示例中为 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))
我有一大组数据,我正在使用 glob.glob(some_file_path.dat)
从我的桌面导入到 jupyter 到 python。这将输出一个列表,其中包含每个数据文件路径作为字符串(总共 1851 个)。我想做的是将这个庞大的列表分成 10 个文本文件(因此 9 个文件将包含 185 个字符串,而 1 个将包含 186 个,因为总共有 1851 个)。我有点不知所措,所以他们根据 'evenly' 进行拆分,指定 10 个文本文件(每个文件的名称不同)作为要拆分的数量。
如有任何帮助,我们将不胜感激。
我发现这个问题之前已经回答过:How do you split a list into evenly sized chunks?
不同之处在于您似乎想要拆分它以便块具有共享的最小大小(在您的示例中为 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))