繁体   English   中英

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

[英]Writing a nested list into a text file?

嘿伙计们 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

在此先感谢,请随时更正我的编码。

您希望在每个项目之间有制表符而不是换行符。 我改变的第二件事是我在内循环之后添加了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()

使用''.join()

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

该代码使用join将列表转换为字符串,然后通过使用\n连接它们来分隔行。

output 是这样的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM