如何在chunk fi中编写列表列表

2024-09-24 02:24:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我的列表如下所示:

listThing = [['apple','mango','cherry'],
             ['dog','cat','bird'],
             ['rose','jasmine','sunflower']
             ['hospital','house','school']
             ['chair','table','cupboard']
             ['book','pencil','pen']]

我想把这个列表写到文件中,其中文件的数量是一个预定的值。然后,每个文件中的列表数就是所有列表数和文件数的除法。所以如果:

number of file = 3
number of list in each file = number of all lists/number of file = 6/3 = 2

输出如下所示:

文件1.txt

apple
mango
cherry
dog
cat
bird

文件2.txt

rose
jasmine
sunflower
hospital
house
school

文件3.txt

chair
table
cupboard
book
pencil
pen

这就是我尝试过的:

import math

allList = len(listThing)
numFile = 3
listInFile = math.ceil(allList/numFile)

for i in range(listInFile):
    with open('file'+str(i)+'.txt', 'w') as out:
        for n in range(listInFile):
            # I don't know what should I do next

我不知道如何解决这个问题。我希望有人能帮我解决这个问题。谢谢


Tags: 文件ofintxtnumberapple列表cat
2条回答
import math    

list_of_lists = [['apple', 'mango', 'cherry'],
                 ['dog', 'cat', 'bird'],
                 ['rose', 'jasmine', 'sunflower'],
                 ['hospital', 'house', 'school'],
                 ['chair', 'table', 'cupboard'],
                 ['book', 'pencil', 'pen']]

num_files = 3
all_lists = len(list_of_lists)

lists_per_file = math.ceil(all_lists / num_files)

for i in range(1, num_files + 1):
    with open("file{}.txt".format(i), "w") as file:
        lst_idx = (i-1)*lists_per_file
        for lst in list_of_lists[lst_idx:lst_idx+lists_per_file]:
            for word in lst:
                file.write("{}\n".format(word))

试试这个:

import math

listThing = [['apple','mango','cherry'],
             ['dog','cat','bird'],
             ['rose','jasmine','sunflower'],
             ['hospital','house','school'],
             ['chair','table','cupboard'],
             ['book','pencil','pen']]

allList = len(listThing)
numFile = 3
listInFile = int(math.ceil(allList/numFile))
currentFileIndex = None

for e, lt in enumerate(listThing):
    fileIndex = 1 + int(math.floor(e / listInFile))
    if currentFileIndex != fileIndex:
        currentFileIndex = fileIndex
        currentFile = open('file%d.txt' % fileIndex, 'wb')
    for entry in lt:
        currentFile.write(entry.encode('utf8'))
        currentFile.write(b'\n')

相关问题 更多 >