繁体   English   中英

在python中将具有3个子列表的列表打印到文件中的最佳方法是什么?

[英]What is the best way to print a list with 3 sublists to a file in python?

我有一个列表“本地化”,其中包含3个子列表。 我想将此列表打印到文件中,每个子列表都在一个列中。

例如:

>>>print localisation

localisation = [['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'i']]

我想要一个看起来像的文件:

a   d   g
b   e   h
c   f   i

(列可以用单个空格,制表符等分隔)

目前,我正在执行以下操作:

with open("rssi.txt") as fd:
    for item in localisation:
        print>>fd, item

有没有更好的方法来做到这一点,例如单行一次打印整个列表?

localisation = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

with open("rssi.txt") as f:
    f.write('\n'.join(' '.join(row) for row in zip(*localisation)))

# a d g
# b e h
# c f i

>>> localisation = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
>>> zip(*localisation)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
with open("rssi.txt", "w") as f:
    for col in zip(*localisation):
        f.write(' '.join(str(x) for x in col) + '\n')

如果内部列表中的每个项目都已经是字符串,则可以只使用' '.join(col) + '\\n' ,以制表符分隔而不是空格,请使用'\\t'.join(...)

暂无
暂无

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

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