【问题标题】:How do I split a large list containing strings into multiple text files [closed]如何将包含字符串的大列表拆分为多个文本文件[关闭]
【发布时间】:2021-12-17 04:04:30
【问题描述】:

我有一大组数据,我正在使用glob.glob(some_file_path.dat) 从我的桌面将它们导入到 jupyter 到 python 中。这会输出一个列表,其中包含每个数据文件路径作为字符串(总共 1851 个)。我想要做的是将这个庞大的列表拆分为 10 个文本文件(因此 9 个文件将包含 185 个字符串,1 个文件将包含 186 个,因为总共有 1851 个)。我有点不知所措如何去做,所以他们通过指定 10 个文本文件(每个名称不同)作为要分割的数字来“均匀地”分割。

任何帮助将不胜感激。

【问题讨论】:

标签: python python-3.x string list text


【解决方案1】:

我发现这个问题之前已经回答过: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))

【讨论】:

  • 非常感谢!以一种可以理解的方式回答并提出类似的问题。它完全符合我的期望!非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
相关资源
最近更新 更多