Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python3打印函数的for循环末尾打印新行?_Python_Python 3.x - Fatal编程技术网

如何在python3打印函数的for循环末尾打印新行?

如何在python3打印函数的for循环末尾打印新行?,python,python-3.x,Python,Python 3.x,我试图为给定输入N的每个案例打印N-queen。为此,我必须显式地编写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:

我试图为给定输入N的每个案例打印N-queen。为此,我必须显式地编写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('-')  
输出:

#One case in n=5

- - Q - -
Q - - - -
- - - Q -
- Q - - -
- - - - Q
由于没有显式地使用条件,我在一行中得到了输出,这是显而易见的

- - Q - - Q - - - - - - - Q - - Q - - - - - - - Q
有没有办法在print函数中的end=''位置隐式写入条件

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

我正在为python 3.4.2使用IDLE。

只需在外循环的末尾打印换行符

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

您是否尝试过打印(,end=('if j!=n-1 else'\n'))?哦,我当然错过了。:)谢谢,它给出了正确的结果。Python太棒了!:“Q”与“-”的DDo相同。让
=
Q'如果j==a[i]-1 else'-'
并且您只需要一个print语句谢谢,但是我希望print函数中的隐式条件代替end=''。@vaultah已经在上面的评论中找到了一种方法。