python - 将任意长度的列表写入文件

标签 python

我有一个表单列表

lssample=[  [ [A,B],[C] ] ,[ [D],[E,F] ],[ [G,H],[I] ]]

将其写入表单的最有效方法是什么

A,B : C
D: E,F
G,H : I

请注意,子列表的长度是任意的。下面的代码只写列表的形式(带括号)。有没有一种将其写入文件的 pythonic 方式?

with open("output1.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(lssample)

最佳答案

这似乎是一种非常简单的格式,只需滚动您自己的编写器,例如:

In [2]: data = [[['A','B'], ['C']], [['D'],['E','F']], [['G','H'], ['I']]]

In [3]: import io

In [4]: with io.StringIO() as f:
    ...:     for record in data:
    ...:         left, right  = map(",".join, record)
    ...:         f.write(f"{left} : {right}\n")
    ...:     final = f.getvalue()
    ...:

In [5]: print(final)
A,B : C
D : E,F
G,H : I

请注意,io.StringIO 只是一个内存缓冲区,为了便于说明,它就像一个文件。你只需要做:

with open("output1.txt", "w") as f:
    ...

当然,您不需要 final = f.getvalue()。此外,我正在使用 Python 3.6 f-strings。如果没有,您可以使用:

f.write("{} : {}".format(left, right)

关于python - 将任意长度的列表写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45492129/

相关文章:

python - 使用整数索引重新采样数据帧

python - 从矩阵中减去转置但保留原始对角线

python - 如何使用 Python 3.5 在 Windows 10 系统上安装 mbed CLI?

python - pandas系列中的缺失值检查

python - 如何从产品名称中提取品牌

python - 谷歌 Dataproc Presto : how to run queries using Python

python - 编写一个可以在 pandas 数据框中从十六进制格式转换为 ascii 格式的函数

python - numpy 索引的错误(?)

python - 无法在 Windows 上使用 git-p4 导入

python - 如何将多个嵌套字典合并为一个