我坚持使用我的程序中的一个函数来格式化由空格分隔的多行数字。到目前为止,下面的代码采用了未格式化的列表列表,并将其分成一个由没有括号的空格分隔的表:
def printMatrix(matrix):
return ('\n'.join(' '.join(map(str, row)) for row in matrix))
我希望所有数字尽管在输出中很好地排列。我无法弄清楚如何将格式运算符粘贴到列表理解中以实现此目的。输入始终是方阵(2x2 3x3等) 以下是该计划的其余部分以澄清
# 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))
main()的
答案 0 :(得分: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)
来解压每一行。
答案 1 :(得分:0)
这样的事情可以解决问题:
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