繁体   English   中英

如何不在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()

我遇到了同样的问题,这就是我所做的: >>> 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=' ', )

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

您可以创建对需要打印的数据进行分区的子列表。 打印eacht部分之前,测试,如果你需要打印一个'\\n'前一行和打印照片,无需partitiones '\\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 ^^^^使用的每个“行”的起始编号(减少 1 但固定在 1 的范围内)
  • enumerate(partitioned)返回序列内的位置和该位置的数据 - 您只想在第一个输出完成后打印'\\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]]

暂无
暂无

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

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