2016-03-06 58 views
0

我是新來的蟒蛇,我有一個小問題,讓我們假設我有以下 陣列:L = [[ 1,2,3,4,5,6,7,8,9,10 ] ,[ 2,5,8,9,6,4,7,3,42,7 ]],我想將它寫入格式下的文本文件:寫矩陣爲Python文件

1 <\t> 2 
2 <\t> 5 
3 <\t> 8 
4 <\t> 9 
5 <\t> 6 
6 <\t> 4 
7 <\t> 7 
8 <\t> 3 
9 <\t> 42 
10 <\t> 7 

任何人都有一個快速解決方案? 我曾嘗試:

L=[[1,2,3,4,5,6,7,8,9,10],[2,5,8,9,6,4,7,3,42,7]] 

thefile=open("testo.txt","w") 

thefile.write("%s \t %s \n" %L[1][:] %L[2][:]) 

,我得到這個錯誤:

thefile.write("%s \t %s \n" %L[1][:] %L[2][:]) 
TypeError: not enough arguments for format string 

謝謝!

回答

0

你幾乎有想法,但是你錯誤的字符串插值語法%,並且使用[:]將打印整個內部列表作爲一個字符串,你需要使用迭代。嘗試:

with open('testo.txt', 'w') as f: 
    for i in range(len(L[1])): 
     f.write("%s \t %s \n" % (L[0][i], L[1][i])) 

或更Python的方式:

with open('testo.txt', 'w') as f: 
    for list_item_1, list_item_2 in zip(*L): 
     f.write("%s \t %s \n" % (list_item_1, list_item_2)) 
+0

我得到這個錯誤:f.write( 「%S \噸%S \ n」 個%L [0] [I],L [1] [i]) TypeError:沒有足夠的參數格式字符串和f.writeline它說屬性不存在 – Mehdi

+0

是的,對不起,我更喜歡'.format()'。它應該是一個元組,請參閱編輯。 – Nikita