2014-10-19 68 views
1

我在我的程序中卡住了一個函數,它格式化了由空格分隔的多行數字。下面的代碼到目前爲止採取列表的格式化列表,並使它變成不帶括號,以空格分隔的表:如何使用列表理解來格式化列表的列表?

def printMatrix(matrix): 
    return ('\n'.join(' '.join(map(str, row)) for row in matrix)) 

我想所有的數字來輸出很好,雖然排隊。我無法弄清楚如何將格式運算符粘貼到列表理解中來實現此目的。輸入總是一個方陣(2×2 3×3等) 這裏的程序的其餘部分,以澄清

# Magic Squares 

def main(): 
    file = "matrix.txt" 
    matrix = readMatrix(file) 
    print(printMatrix(matrix)) 
    result1 = colSum(matrix) 
    result2 = rowSum(matrix) 
    result3 = list(diagonalSums(matrix)) 
    sumList = result1 + result2 + result3 
    check = checkSums(sumList) 
    if check == True: 
     print("This matrix is a magic square.") 
    else: 
     print("This matrix is NOT a magic square.") 
def readMatrix(file): 
    contents = open(file).read() 
    with open(file) as contents: 
     return [[int(item) for item in line.split()] for line in contents] 




def colSum(matrix): 
    answer = [] 
    for column in range(len(matrix[0])): 
     t = 0 
     for row in matrix: 
      t += row[column] 
     answer.append(t) 
    return answer 

def rowSum(matrix): 
    return [sum(column) for column in matrix] 


def diagonalSums(matrix): 
    l = len(matrix[0]) 
    diag1 = [matrix[i][i] for i in range(l)]   
    diag2 = [matrix[l-1-i][i] for i in range(l-1,-1,-1)] 
    return sum(diag1), sum(diag2) 


def checkSums(sumList): 
    return all(x == sumList[0] for x in sumList) 

def printMatrix(matrix): 
    return ('\n'.join(' '.join(map(str, row)) for row in matrix)) 

主()

+0

我認爲你可能會發現這個線索有用http://stackoverflow.com/questions/13214809/pretty-print-2d-python-list – user3378649 2014-10-19 23:16:52

+0

一些示例輸入?我認爲行的長度有所不同? – 2014-10-19 23:18:13

回答

1
def printMatrix(matrix): 
    return "\n".join((("{:<10}"*len(row)).format(*row))for row in matrix) 


In [19]: arr=[[1,332,3,44,5],[6,7,8,9,100]] 

In [20]: print(printMatrix(arr)) 
1   332  3   44  5   
6   7   8   9   100 

"{:<10}"*len(row))創建{}每個數字左對齊10 <:10然後我們使用str.format format(*row)來解壓每一行。

0

像這樣的事情768,16做的伎倆:

def print_matrix(matrix, pad_string=' ', padding_ammount=1, 
       number_delimiter=' ', number_width=3): 
    ''' 
    Converts a list of lists holding integers to a string table. 
    ''' 

    format_expr = '{{:{}>{}d}}'.format(number_delimiter, number_width) 
    padding = pad_string * padding_ammount 
    result = '' 
    for row in matrix: 
     for col in row: 
      result = '{}{}{}'.format(
       result, 
       padding, 
       format_expr 
      ).format(col) 
     result = '{}\n'.format(result) 
    return result 

a = [ 
    [1, 2, 3, 22, 450], 
    [333, 21, 13, 5, 7] 
] 

print(print_matrix(a)) 
# 1 2 3 22 450 
# 333 21 13 5 7 

print(print_matrix(a, number_delimiter=0) 
# 001 002 003 022 450 
# 333 021 013 005 007