簡體   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