调用打印的函数,避免换行

时间:2015-03-26 13:08:22

标签: python python-2.7

我有打印数组的函数:

In [93]:

printArr(arrs[0], Nrows, Ncols)
# # #  
# # #  
# # #  
O O O  
O O O  
O O O 

printArr 函数中,我在该函数调用pythons print 函数的末尾添加一个逗号(,),以获得3列的输出。

但是,如果我想多次调用 printArr ,并将输出堆叠到列中,该怎么办?

# # #    O O O 
# # #    # # #
# # #    # # #
O O O    O O O
O O O    O O O
O O O    O O O

printArr 的两次调用只是给了我这个

In [96]:

printArr(arrs[0], Nrows, Ncols)
print " "
printArr(arrs[1], Nrows, Ncols)    
​
# # #  
# # #  
# # #  
O O O  
O O O  
O O O  

O O O  
# # #  
# # #  
# # #  
O O O  
O O O  

有没有办法实现这一目标,还是我必须重做我的整个 printArr 功能?

由于

编辑: 好的,这是我的 printArr 功能

def printArr(arr, Nrows, Ncols):
    for row in range(0, Nrows):
        for col in range(0, Ncols):
            if arr[row][col] == 1:
                print '#',
            else:
                print 'O',
        print " "

它需要一个三维Ndarray作为输入,我打算使用该函数以一种很好的方式打印该数组中的所有矩阵(例如,总共3列和总共3行)

再次感谢

2 个答案:

答案 0 :(得分:1)

def printArrays(listOfArrays,cols):
    splittedArrays = [[array[x:x+cols] for x in range(0,len(array),cols)] for array in listOfArrays]
    c = list(zip(*splittedArrays))
    c = ["".join([[" "+"".join(y)][0]for y in x]) for x in c]
    print("\n".join([" ".join(array) for array in c]))

a =["a","b","c","a","b","c"]
b= ["x","y","z","x","y","z"]
printArrays([a,b],3)
printArrays([a,b],2)

答案 1 :(得分:0)

您可以创建一个行生成器并在打印函数中使用它:

def rows(arr):
    for row in arr:
        yield " ".join('#' if c == 1 else 'O' for c in row)

def printArr(arr):
    print "\n".join(rows(arr))

from itertools import izip_longest
def print2Arr(arr1, cols1, arr2, cols2):
    for row1, row2 in izip_longest(rows(arr1), rows(arr2)):
        row1 = row1 or " " * (2 * cols1 - 1)
        row2 = row2 or " " * (2 * cols2 - 1)
        print row1 + "    " + row2

示例:

>>> arr1 = [[1, 0, 0], [1, 1, 0]]
>>> arr2 = [[1, 0, 0], [1, 1, 0], [1, 0, 0]]
>>> printArr(arr1)
# O O
# # O
>>> print2Arr(arr1, 3, arr2, 3)
# O O    # O O
# # O    # # O
         # O O
>>> print2Arr(arr2, 3, arr1, 3)
# O O    # O O
# # O    # # O
# O O