将嵌套列表写入文本文件?

2024-09-21 01:17:52 发布

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

嘿,伙计们,这里的python新手,如果我运行以下代码:

test = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

with open('listfile.txt', 'w') as file:
    for item in test:
        for i in range(2):
            file.write("%s" % item)
            file.write("\n")

文本文件如下所示:

['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']

关于如何使其看起来像这样的任何帮助:

a    b    c
a    b    c
a    b    c
a    b    c

提前感谢,请随时更正我的编码


Tags: 代码intesttxtforaswithrange
3条回答

使用^{}

with open('listfile.txt', 'w') as file:
    file.write('\n'.join('  '.join(item) for item in test))

您希望在每个项目之间有选项卡,而不是换行符。我更改的第二件事是在内部循环之后添加file.write("\n"),以便在每行之间有一条新行。最后,我添加了file.close()来关闭文件

test = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

with open('listfile.txt', 'w') as file:
    for item in test:
        for i in range(len(item)):
            file.write("%s" % item[i])
            file.write("\t") # having tab rather than "\n" for newline. 
        file.write("\n")
file.close()
with open('listfile.txt', 'w') as file:
    file.write('\n'.join(' '.join(map(str, lett)) for lett in test))

代码将列表转换为带有join的字符串,然后通过使用\n连接行来分隔行

输出如下:

a b c
a b c
a b c
a b c

看起来您需要选项卡,因此可以使用\t而不是' '加入:

test = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

with open('listfile.txt', 'w') as file:
    file.write('\n'.join('\t'.join(map(str, sl)) for sl in test))

哪个输出:

a   b   c
a   b   c
a   b   c
a   b   c

相关问题 更多 >

    热门问题