Thanks beforehand. I'm currently trying to get some values from an array in the format that another program requieres as input. I'm iterating over i rows and j columns since I need the value of i directly followed by the value of array[i,j] (if non-zero and i different than j) printed directly on the same line for each value on the first dimension. I also need to jump to the next line only for a new value of i. I've achieved it with a normal jump line "\n", but it leaves a blank line and I need the next line to be directly under the previous with no blank line. I know I could easily fix this in bash but I'd like to know a method to do it in python.
This is what I'm trying and the result:
import numpy as np
z=np.arange(100).reshape(10,10)
z[5,4]=0
print z
for i in xrange(1,10,1):
for j in xrange(1,10,1):
if not (i==j):
if not z[i,j]==0:
print j, z[i,j],
print "\n"
[[ 0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]
[20 21 22 23 24 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 0 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
2 12 3 13 4 14 5 15 6 16 7 17 8 18 9 19
1 21 3 23 4 24 5 25 6 26 7 27 8 28 9 29
1 31 2 32 4 34 5 35 6 36 7 37 8 38 9 39
1 41 2 42 3 43 5 45 6 46 7 47 8 48 9 49
1 51 2 52 3 53 6 56 7 57 8 58 9 59
1 61 2 62 3 63 4 64 5 65 7 67 8 68 9 69
1 71 2 72 3 73 4 74 5 75 6 76 8 78 9 79
1 81 2 82 3 83 4 84 5 85 6 86 7 87 9 89
1 91 2 92 3 93 4 94 5 95 6 96 7 97 8 98
A call to print automatically adds a newline at the end of what it prints. You can suppress the newline by adding a comma at the end as you have done. However in your call to print '\n'
at the end of the loop, you are adding two newlines because print adds a newline to the end of your '\n'. Either end this print statement with a comma or print the empty string, either will work:
import numpy as np
z=np.arange(100).reshape(10,10)
z[5,4]=0
print z
for i in xrange(1,10,1):
for j in xrange(1,10,1):
if not (i==j):
if not z[i,j]==0:
print j, z[i,j],
print "" # automatically adds newline to end of empty string.
# print "\n", # <---- could use this alternatively. Note the comma at the end