繁体   English   中英

在一系列次安全打印之后如何在另一个打印上方直接打印,而又在python 2中不留空白?

[英]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 [i,j]值(如果非零且i与j不同)直接跟在i的值之后第一维。 我还需要仅针对新值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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM