jrlen balane wrote:
so for example, i have 5 arrays, i can do this (is this correct):

data1[1,2,3,4,5 (and so on)]
data2[1,2,3,4,5 (and so on)]
data3[1,2,3,4,5 (and so on)]
data4[1,2,3,4,5 (and so on)]
data5[1,2,3,4,5 (and so on)]
datas = [data1, data2, data3, data4, data5]

for data in datas:
lines.append('\t'.join(data) + '\n') =================================
(supposed to be output)
1 2 3 4 5 ...
1 2 3 4 5 ...
1 2 3 4 5 ...
...


(but i want this output)
1    1    1     1    1
2    2    2     2    2
3    3    3     3    3
...   ...  ...   ...    ...
=================================

You need to reformat your data. zip() is handy for this. Given multiple lists as arguments, zip() creates tuples from the first element of each list, the second element of each list, etc:


 >>> a=[1,2,3]
 >>> b=[11,22,33]
 >>> zip(a, b)
[(1, 11), (2, 22), (3, 33)]

When all the source lists are themselves in a list, you can use the *args form 
of argument passing:

 >>> c=[a, b]
 >>> c
[[1, 2, 3], [11, 22, 33]]
 >>> zip(*c)
[(1, 11), (2, 22), (3, 33)]

So in your case this will do what you want:
for data in zip(*datas):
    lines.append('\t'.join(data) + '\n')

If datas is large you might want to use itertools.izip() instead. zip() creates an intermediate list while izip() creates an iterator over the new tuples, so it is more memory-efficient.


output_file = file('c:/output.txt', 'w') output_file.writelines(lines) output_file.close() =================================

how am i going to change the filename automaticaly?
for example:
#every 5 minutes, i am going to create a file based on the data above
for i in range(100) output_file = file('c:/output' +.join(i) +'.txt', 'w') #guess this won't work
output_file.writelines(lines)
output_file.close()

Two ways to do this: >>> for i in range(5): ... print 'c:/output' + str(i) + '.txt' ... print 'c:/output%d.txt' % i ... c:/output0.txt c:/output0.txt c:/output1.txt c:/output1.txt ...

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to