简体   繁体   English

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

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

I have a list "localisation" which contains 3 sublists. 我有一个列表“本地化”,其中包含3个子列表。 I want to print this list to a file with each sublist in a column. 我想将此列表打印到文件中,每个子列表都在一个列中。

eg: 例如:

>>>print localisation

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

I want a file that looks like: 我想要一个看起来像的文件:

a   d   g
b   e   h
c   f   i

(columns can be separated by a single space, a tab etc) (列可以用单个空格,制表符等分隔)

At the moment I am doing it as follows: 目前,我正在执行以下操作:

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

Is there a better way of doing it eg a single line that prints the whole list in at one time? 有没有更好的方法来做到这一点,例如单行一次打印整个列表?

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')

If every item in your inner list is already a string you can just use ' '.join(col) + '\\n' , to separate by tabs instead of spaces use '\\t'.join(...) . 如果内部列表中的每个项目都已经是字符串,则可以只使用' '.join(col) + '\\n' ,以制表符分隔而不是空格,请使用'\\t'.join(...)

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

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