如何在for循环的语句末尾不打印换行符

how to not print newline at end of statement in for loop

r, c = input().split()
r=int(r)
c=int(c)
list1=[]
v=1
for i in range(r):
    list2=[]
    for j in range(c):
        list2.append(v)
        v=v+1
    list1.append(list2)


for i in range(r):
    for j in range(c):
        print(list1[i][j],end=" ")
    print()        

这是一张显示实际输出和输出我的图像 我得到:

问题是您需要跳过最外层循环末尾的换行符和每行末尾的空格。对于一般的迭代器,这需要一些额外的工作,但对于您的简单情况,只需检查 ij 就足够了:

for i in range(r):
    for j in range(c):
        print(list1[i][j], end=" " if j < c - 1 else "")
    if i < r - 1:
        print()

您可以创建子列表来划分您需要打印的数据。 在打印每个部分之前,测试是否需要为前一行打印 '\n' 并打印没有 '\n':

的分区
r, c = map(int, input().split())

# create the parts that go into each line as sublist inside partitioned
partitioned = [ list(range(i+1,i+c+1)) for i in range(0,r*c,c)]
#                       ^^^^ 1 ^^^^              ^^^^ 2 ^^^^

for i,data in enumerate(partitioned):
    if i>0: # we need to print a newline after what we printed last
        print("")

    print(*data, sep = " ", end = "") # print sublist with spaces between numbers and no \n
  • ^^^^ 1 ^^^^ 为每个分区创建您需要打印的所有数字的范围
  • ^^^^ 2 ^^^^ 创建 ^^^^ 1 ^^^^ 中使用的每个 "row" 的起始数字(减少 1 但固定在 1 的范围内)
  • enumerate(partitioned) returns 序列内​​的位置和该位置的数据 - 您只想在第一个输出完成后打印 '\n'

在最后一个 partitioned 之后 - 输出 for ... 完成并且不会再次输入 - 因此后面没有 \n。


'6 3' 的输出(为清楚起见添加\n):

1 2 3\n
4 5 6\n
7 8 9\n
10 11 12\n
13 14 15\n
16 17 18

其中 partitioned 为:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]

我遇到了同样的问题,我是这样做的: >>> help(print)

Help on built-in function print in module builtins:
print(...)

    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

我是 python 的新手,但这是我用来消除打印语句末尾新行的代码:

for ch in message:
    print (ord(ch), end=' ')

如果我想删除每行语句末尾的 ' ',因为它来自默认值 (sep=" "),那么我将使用以下内容:

for ch in message:
        print (ord(ch), ch, sep = '' if ch==message[-1] else ' ', end=' ', )

#请注意消息是一个字符串。