2013-04-05 19 views
2

我有一個包含3個子列表的「本地化」列表。我想將此列表打印到列中每個子列表的文件中。什麼是最好的方式來打印列表與3個子列表到Python中的文件?

如:

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

有沒有更好的方法來做到這一點,例如一次只打印整個列表的單行?

+2

那麼,你現有的代碼不會產生你描述的輸出,所以是的,有更好的方法。 – geoffspear 2013-04-05 16:37:04

回答

4
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')] 
+0

+1;準備親自寫這篇文章,並對你的舊版本錯誤發表評論。 – geoffspear 2013-04-05 16:39:23

+0

快速挑選:不要在代碼中使用'fd'作爲文件句柄的名稱。 'fd'通常表示一個文件描述符,它是一個在低級I/O操作中使用的整數。更高級別的操作使用'open'返回的對象,它們是文件句柄。 – DaveTheScientist 2013-04-05 17:43:48

0
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(...)

+1

這不是運營商試圖做的事情;因此「與列中的每個子列表」 – 2013-04-05 16:38:48

+0

@PiotrHajduga哎呀,謝謝。編輯來解決這個問題。 – 2013-04-05 16:40:30

相關問題