python 将拆分列表存储到同一行中的多个文件和项目中

python store a split list into multiple files and items in same line

我有一个包含 9000 项的庞大列表。我已经提到了这个 post here and here。不要将其标记为重复

Mylist = [1234,45678,2314,65474,412,87986,21321,4324,68768,1133,712421,12132,0898]

我想拆分列表并将每个列表的输出存储在记事本文件中

例如:我希望我的每个输出列表都包含原始 Mylist

中约 10% 的项目

所以,我尝试了以下

for k,g in itertools.groupby(Mylist, lambda x: x/10):
      with open("part1.txt", 'w') as file:
      file.write('\n'.join(yourList))

我希望我的输出有多个文本文件,如下所示,每个文件应包含 10% 的项目,如下所示,原始列表的屏幕截图

part1.txt
part2.txt
part3.txt
part4.txt

不需要groupby,一个带切片的简单循环就足够了。您需要决定如何处理额外的项目(添加到最后一个列表或添加一个额外的文件):

Mylist = [1234,45678,2314,65474,412,87986,21321,4324,68768,1133,712421,12132,898]
N = 3 # use 10 in your real life example

step = len(Mylist)//N
start = 0
for i, stop in enumerate(range(step, len(Mylist)+step, step)):
    print(f'file{i}')
    print(Mylist[start:stop]) # save to file here instead
    start = stop

输出:

file0
[1234, 45678, 2314, 65474]
file1
[412, 87986, 21321, 4324]
file2
[68768, 1133, 712421, 12132]
file3
[898]

添加到最后一个文件的变体:

Mylist = [1234,45678,2314,65474,412,87986,21321,4324,68768,1133,712421,12132,898]
N = 3

step = len(Mylist)//N
start = 0

for i, stop in enumerate(range(step, len(Mylist), step)):
    print(f'file{i}')
    if i+1 == N:
        stop = len(Mylist)
    print(Mylist[start:stop]) # save to file here instead
    start = stop

输出:

file0
[1234, 45678, 2314, 65474]
file1
[412, 87986, 21321, 4324]
file2
[68768, 1133, 712421, 12132, 898]
保存到文件
Mylist = [1234,45678,2314,65474,412,87986,21321,4324,68768,1133,712421,12132,898]
N = 3

step = len(Mylist)//N
start = 0

for i, stop in enumerate(range(step, len(Mylist), step), start=1):
    if i == N:
        stop = len(Mylist)
    with open(f'file{i}.txt', 'w') as f:
        f.write(','.join(map(str,Mylist[start:stop])))
    start = stop