数组生成文本文件格式

0 投票
3 回答
1052 浏览
提问于 2025-04-15 13:30

我有几个数组,我想把它们以特定的格式写入文本文件,比如说,

“现在的格式”

a= [1 2 3 4 5 ]

b= [ 1 2 3 4 5 6 7 8 ]  

c= [ 8 9 10 12 23 43 45 56 76 78]

d= [ 1 2 3 4 5 6 7 8 45 56 76 78 12 23 43 ]

在文本文件中需要的“格式”,

   a   '\t'    b      '\t'     d  '\t'    c

   1   '\t'    1  

   2    '\t'   2  

   3    '\t'   3  

   4    '\t'   4  

   5   '\t'    5  

      6   

      7              

      8        

'\t' - 代表一个制表符的空格

问题是,

我现在的数组是线性排列的[a]、[b]、[c]和[d],我需要把它们转换成“需要的格式”,并且要对[a]、[b]、[d]和[c]进行排序,然后把它们写入一个文本文件中。

3 个回答

1

看看 matplotlib.mlab.rec2csv 和 csv2rec 这两个函数:

>>> from matplotlib.mlab import rec2csv,csv2rec
# note: these are also imported automatically when you do ipython -pylab

>>> rec = csv2rec('csv file.csv')
>>> rec2csv(rec, 'copy csv file', delimiter='\t')
6
from __future__ import with_statement
import csv
import itertools



a= [1, 2, 3, 4, 5]
b= [1, 2, 3, 4, 5, 6, 7, 8]
c= [8, 9, 10, 12, 23, 43, 45, 56, 76, 78]
d= [1, 2, 3, 4, 5, 6, 7, 8, 45, 56, 76, 78, 12, 23, 43]

with open('destination.txt', 'w') as f:
    cf = csv.writer(f, delimiter='\t')
    cf.writerow(['a', 'b', 'd', 'c']) # header  
    cf.writerows(itertools.izip_longest(a, b, d, c))

destination.txt 文件中的结果是这样的(<tab> 实际上是文件中的真实制表符):

a<tab>b<tab>d<tab>c
1<tab>1<tab>1<tab>8
2<tab>2<tab>2<tab>9
3<tab>3<tab>3<tab>10
4<tab>4<tab>4<tab>12
5<tab>5<tab>5<tab>23
<tab>6<tab>6<tab>43
<tab>7<tab>7<tab>45
<tab>8<tab>8<tab>56
<tab><tab>45<tab>76
<tab><tab>56<tab>78
<tab><tab>76<tab>
<tab><tab>78<tab>
<tab><tab>12<tab>
<tab><tab>23<tab>
<tab><tab>43<tab>

这是 izip_longest 函数,如果你的 Python 版本低于 2.6:

def izip_longest(*iterables, fillvalue=None):
    def sentinel(counter=([fillvalue]*(len(iterables)-1)).pop):
        yield counter()
    fillers = itertools.repeat(fillvalue)
    iters = [itertools.chain(it, sentinel(), fillers) 
             for it in iterables]
    try:
        for tup in itertools.izip(*iters):
            yield tup
    except IndexError:
        pass
-1

这段代码是为了好玩而写的,没有使用任何外部库:

a= [1, 2, 3, 4, 5]
b= [1, 2, 3, 4, 5, 6, 7, 8]
c= [8, 9, 10, 12, 23, 43, 45, 56, 76, 78]
d= [1, 2, 3, 4, 5, 6, 7, 8, 45, 56, 76, 78, 12, 23, 43]

fh = open("out.txt","w")

# header line
fh.write("a\tb\td\tc\n")
# rest of file
for i in map(lambda *row: [elem or "" for elem in row], *[a,b,d,c]):
  fh.write("\t".join(map(str,i))+"\n")

fh.close()

撰写回答