将两个长度不同的列表作为列写入数据文件

时间:2012-11-13 10:53:55

标签: python list

我正在考虑两个清单:     a = [2, 4, 7]     b = [6, 9, 10, 90, 80]

我想将这些列表写入数据文件,以在一列中显示列表'a'的元素,并在第二列中显示'b'的元素,同时考虑到a和b的长度不同。

2 个答案:

答案 0 :(得分: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 :(得分: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))