2012-11-13 46 views
1

我正在考慮這兩個名單: a = [2, 4, 7] b = [6, 9, 10, 90, 80]編寫不同長度的兩個列表的列數據文件

我想寫這些列表的數據文件顯示列表的元素「A」的考慮到a和b的長度不相同,第二列中的'b'列和'b'。

+0

我不明白你真正想要的。 – alexvassel

+0

而不是使用固定長度的列,用分隔符分隔字段,如逗號。讀取文件時,用分隔符(逗號)分隔每行。 – Zesty

回答

1

差別小的變化,從@eumiro

with open("test.txt","w") as fin: 
    #izip_longest create consecutive tuples of elements from the list of iterables 
    #where if any of the iterable's length is less than the longest length of the 
    #iterable, fillvalue is taken as default 
    #If you need formatted output, you can use str.format 
    #The format specifier here used specifies the length of each column 
    #to be five and '^' indicates that the values would be center alligned 
    for e in izip_longest(a,b,fillvalue=''): 
     print >>fin,"{:^5} {:^5}".format(*e) 
     #if you are using Python 3.x 
     #fin.write("{:^5} {:^5}\n".format(*e)) 
+0

Urgh。不要使用'print >>' – katrielalex

6
import itertools as it 
import csv 

with open('output.csv', 'w') as f: 
    csvw = csv.writer(f) 
    for aa, bb in it.izip_longest(a, b): 
     csvw.writerow(aa, bb) 

或較短的版本由@katriealex啓發:

with open('output.csv', 'w') as f: 
    csv.writer(f).writerows(it.izip_longest(a, b)) 
+1

'作家'採取一個參數(行)和'csvw.writerows'甚至更整潔=) – katrielalex

+0

您的腳本給我列用逗號分隔,這不是我需要的 – CharlieShe

相關問題