I have an output (a long one!) from some function, which looks in this way:
[[(0.0, 1.0, 2.0), (1.0, 2.0, 0.0), (2.0, 1.0, 0.0)], [(1.6324986294474886e-06, 1.000000272083105, 1.9999992744450537), (1.0, 1.9999985559929883, 9.626713411705526e-07), (1.9999957124111243, 1.000000714598146, 9.527975279416402e-07)], ......................, [(0.00016488526381860965, 1.0000274825531668, 1.9999267116402146), (0.9999999810184469, 1.9998541492231847, 9.723903843230245e-05), (1.9995669148822666, 1.000072183688789, 9.62532545797885e-05)]]
I don't like the structure of the output, but it is very convenient to use it in the function, which returns it.
But i need to format the output to look this way:
0.0 1.0 2.0 A
1.0 2.0 0.0 B
2.0 1.0 0.0 C
1.6324986294474886e-06 1.000000272083105 1.9999992744450537 A
1.0 1.9999985559929883 9.626713411705526e-07 B
1.9999957124111243 1.000000714598146 9.527975279416402e-07 C
I have this code:
obj = 'A', 'B', 'C'
for n in results():
for z in range(len(results()[0])):
k = n[z], obj[z]
print '\t'.join(map(str, k))
('results' is the name of the function, which returns the big list)
It gives me this:
(0.0, 1.0, 2.0) A
(1.0, 2.0, 0.0) B
(2.0, 1.0, 0.0) C
(1.6324986294474886e-06, 1.000000272083105, 1.9999992744450537) A
(1.0, 1.9999985559929883, 9.626713411705526e-07) B
(1.9999957124111243, 1.000000714598146, 9.527975279416402e-07) C
I can get this, if I don't add the letter (A, B or C) in the end of the line with this code, so, I thought, maybe to add it somehow differently?
Anyway, hoping for your help! Thanks in advance!
An unexpected problem... I really want to write the output into a .csv file, so instead of print I use (for now I've chosen the option of using list and appending the letter, as it is more clear to me)
with open('table.csv', 'wb') as f:
writer = csv.writer(f)
for n in results():
for z in range(len(res[0])):
k = list(n[z])
k.append(obj[z])
writer.writerows ('\t'.join(map(str, k)))
And it doesn't actually work properly, I only get this:
0
.
0
1
.
0
2
.
0
A
.
.
.
Why do I get so strange formatting, but not what I get with print? It is quite shocking to me...
If its always going to be of length 3, you should look into the
itertools
module. Something like:Also, I hope youre not actually using
for z in range(len(results()[0])):
, as that will rerun the results function, recalculating the entire list. Just FYI.The complete program:
The output:
This was checked with python 2.5, 2.6, 2.7 and 3.2.
The implementation adds the letter to the list. (The list constructor is needed, because a tuple is constant and cannot be changed.)
Replace your call to str in the map call to calling a wee function: