python - How to format a list of lists using list comprehension? -
i'm stuck on function in programme formats multiple lines of numbers seperated spaces. next code far takes unformatted list of lists , makes table seperated spaces without brackets:
def printmatrix(matrix): homecoming ('\n'.join(' '.join(map(str, row)) row in matrix))
i of numbers line nicely though in output. can't figure out how stick format operator list comprehension create happen. input square matrix (2x2 3x3 etc) here's rest of programme clarify
# 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 magic square.") else: print("this matrix not magic square.") def readmatrix(file): contents = open(file).read() open(file) contents: homecoming [[int(item) item in line.split()] line in contents] def colsum(matrix): reply = [] column in range(len(matrix[0])): t = 0 row in matrix: t += row[column] answer.append(t) homecoming reply def rowsum(matrix): homecoming [sum(column) column in matrix] def diagonalsums(matrix): l = len(matrix[0]) diag1 = [matrix[i][i] in range(l)] diag2 = [matrix[l-1-i][i] in range(l-1,-1,-1)] homecoming sum(diag1), sum(diag2) def checksums(sumlist): homecoming all(x == sumlist[0] x in sumlist) def printmatrix(matrix): homecoming ('\n'.join(' '.join(map(str, row)) row in matrix))
main()
def printmatrix(matrix): homecoming "\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))
creates {}
each number left aligned 10 <:10
utilize str.format format(*row)
unpack each row.
python list matrix
No comments:
Post a Comment