简体   繁体   English

如何在python3打印功能的for循环的末尾打印新行?

[英]How do I print new line at the end of the for loop in python3 print function?

I am trying to print N-queen for every case for given input n. 我正在尝试在给定输入n的每种情况下打印N-queen。 For this I have to write the condition explicitly for j=n-1 to get a new line after every 'n' columns. 为此,我必须明确地写出j = n-1的条件,以便在每'n'列之后添加新行。

for i in range(n):
    for j in range(n):
        if j!=n-1:
            if j==a[i]-1:
                print('Q',end=' ')
            else:
                print('-',end=' ')
        else:
            if j==a[i]-1:
                print('Q')
            else:
                print('-')  

Output: 输出:

#One case in n=5

- - Q - -
Q - - - -
- - - Q -
- Q - - -
- - - - Q

For not using condition explicitly I get the output in one line, which is obvious. 对于未明确使用条件的情况,我将输出放在一行中,这很明显。

- - Q - - Q - - - - - - - Q - - Q - - - - - - - Q

Is there any way to implicitly write condition in print function in the place of end=' '? 有什么方法可以在end =''位置隐式地在print函数中写入条件吗?

for i in range(n):
    for j in range(n):
        if j==a[i]-1:
            print('Q',(end=' ' if j!=n-1)) #this is not correct
        else:
            print('-',if j!=n-1: end=' ' ) #also not correct

I am using IDLE for python 3.4.2. 我正在使用IDLE for python 3.4.2。

Just print the newline at the end of the outer loop. 只需在外部循环的末尾打印换行符即可。

for i in range(n):
    for j in range(n):
         ...
    print()

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

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