我没有:数组,我喜欢把它带到特定格式的文本文件中,例如,
'现在形式'
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 ]
txt文件中的“必需格式”
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'
- 1个标签空间
问题是,
我有线性形式的数组[a],[b],[c]和d,我必须转置('必需格式')并排序[a],[b],[d]和[c]并将其写为txt文件
答案 0 :(得分: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>
s 实际上是文件中的真实标签):
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&lt; 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 :(得分: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')
答案 2 :(得分:-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()