如何在一系列后续打印后直接在另一张打印件上方打印但不在 python 2 中留下空白 space?

How to print directly above another print after a series of subsecuent prints but without leaving a blank space in python 2?

先谢谢了。 我目前正在尝试以另一个程序需要作为输入的格式从数组中获取一些值。我正在遍历 i 行和 j 列,因为我需要 i 的值直接跟在 array[i,j] 的值(如果非零且 i 不同于 j)直接打印在同一行上的每个值第一个维度。我还需要只为 i 的新值跳转到下一行。我用普通的跳转行“\n”实现了它,但它留下了一个空行,我需要下一行直接在前一行的下面,没有空行。我知道我可以在 bash 中轻松解决此问题,但我想知道在 python.

中执行此操作的方法

这就是我正在尝试的结果:

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 

打印调用会自动在打印内容末尾添加换行符。您可以通过在末尾添加逗号来取消换行。但是,在循环结束时调用 print '\n' 时,您要添加两个换行符,因为 print 会在 '\n' 的末尾添加一个换行符。以逗号结束此打印语句或打印空字符串,两者都有效:

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