【发布时间】:2021-10-09 13:24:14
【问题描述】:
我有这样的 if/else 语句:
import numpy as np
rows_b = int(input("Enter the number of rows of matrix B : " ))
column_b = int(input("Enter the number of columns of matrix B : "))
print("Input elements of matrix B1:")
B1= [[float(input()) for i in range(column_b)] for j in range(rows_b)]
print("Input elements of matrix B2:")
B2= [[float(input()) for i in range(column_b)] for j in range(rows_b)]
b1 = np.array(B1)
b2 = np.array(B2)
result = np.all(b1 == b2[0])
if result:
print('matrix B1 = B2')
#if matrix B1 = B2, go to the next algorithm
else:
print('matrix B1 and B2 are not equivalent')
#if B1 and B2 are not equivalent, stop here.
B = np.array(B1)
print("Matrix B is: ")
for x in B:
print(x)
我想如果 B1 = B2 然后继续下一步(B = np.array (B1))但是(否则)如果 B1 和 B2 不相等则停止算法(不继续 B = np.array (B1 )),怎么样?
【问题讨论】:
-
要么将
B = np.array(B1)的其余代码保留在if条件内,要么使用exit()inelse部分。 -
强制警告:你不能compare floating point值!您需要将其与 epsilon 或
isclosein numpy 进行比较。 -
@ThePyGuy 不,
exit不是要走的路。引用documentation ofexitandquit:“它们对交互式解释器外壳很有用,不应该在程序中使用。” -
@Matthias,这也是
True。exit不是推荐的方式
标签: python matrix conditional-statements