[英]How to print two input lists within a list in separate lines without using NumPy?
我有一个程序,它添加两个矩阵(列表)并打印总和。 首先,程序要求指定行数和列数作为矩阵的维数。
然后它要求输入指定数量的数字作为行和列,如下所示:
dimension: 2 3
numbers in the list: 1 2 3
numbers in the list: 4 5 6
dimension: 2 3
numbers in the list: 7 8 9
numbers in the list: 7 8 9
我试图完全按照以下格式打印两个输入列表(矩阵)的总和 - 两行,三列,不带方括号:
8 10 12
11 13 15
但最终得到这个输出:
[8, 11, 10, 13, 12, 15]
我已经尝试了其他类似帖子中建议的其他几种解决方案,但未能使它们起作用。
不使用NumPy
、 map()
或lambda
函数,如何获得所需的输出?
# input the number of rows and columns (dimensions of the matrix)
rows_cols = input().split()
# save the dimensions as integers in a list
matrix_dim = [int(i) for i in rows_cols]
numbers = 0
matrix_A = []
matrix_B = []
matrices = []
# take the row times the input for the rows of matrix_A
for _ in range(matrix_dim[0]):
numbers = input().split()
matrix_A.append([int(i) for i in numbers])
rows_cols = input().split()
matrix_dim = [int(i) for i in rows_cols]
# take the row times the input for the rows of matrix_B
for _ in range(matrix_dim[0]):
numbers = input().split()
matrix_B.append([int(i) for i in numbers])
# add matrices matrix_A and matrix_B
matrices = [matrix_A[i][k] + matrix_B[i][k] for k in range(len(matrix_A[0])) for i in range(len(matrix_A))]
# print ERROR if the number of columns entered exceed the input number for columns
if len(numbers) != matrix_dim[1]:
print("ERROR")
else:
print(matrices)
您所要做的就是改变对矩阵求和的方式:
matrices = [[matrix_A[i][k] + matrix_B[i][k] for k in range(len(Matrix_A[0]))] for i in range(len(matrix_A))]
然后打印:
for row in matrices:
# print(row)
print(" ".join(row))
或者
from pprint import pprint
pprint(matrices)
最简单的方法是从 nathan 建议的修复开始:
matrices = [[matrix_A[i][k] + matrix_B[i][k] for k in range(len(Matrix_A[0]))] for i in range(len(matrix_A))]
这给你一个二维数组而不是一维数组
[[a, b, c], [d, e, f]]
但现在我们需要很好地打印它。 这是一个将矩阵转换为漂亮字符串的函数:
def prettyString(matrix):
result = ''
for row in matrix:
for value in row:
result += value
result += '\n'
return result
最后,在您的代码中,您可以使用新函数:
print(prettyString(matrices))
尝试这个 -
首先计算列表的总和列表作为输出,然后用空格连接子列表的元素,并用\\n
(换行符)连接这些子列表字符串。 当你打印它时,它会一次打印出一个子列表。
output = [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]
print_out = '\n'.join([' '.join([str(j) for j in i]) for i in output])
print(print_out)
#sample output
1 2 3
4 5 6
当您尝试组合列表列表时,zip 函数会很有帮助。 这适用于任何 nxm 矩阵。
m1 = [
[1,2,3],
[4,5,6]]
m2 = [
[7,8,9],
[7,8,9]]
for row1,row2 in zip(m1,m2):
print(*[el1+el2 for el1,el2 in zip(row1,row2)])
输出:
8 10 12
11 13 15
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.