1

我正在考虑以下两个列表: a = [2, 4, 7] b = [6, 9, 10, 90, 80]

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

4

2 回答 2

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))
于 2012-11-13T10:56:15.520 回答
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))
于 2012-11-13T11:02:55.457 回答