您好!我正在创建一个使用矩阵求解SLAE的程序。矩阵如下:
a11 + a12 + ... + a1n = b1
a21 + a22 + ... + a2n = b2
.........................
an1 + an2 + ... + ann = bn
矩阵的顺序和变量的数量事先未知,因此需要使用exec
函数自动生成:
rows = float(input("Enter the number of rows: "))
columns = float(input("Enter the number of columns: "))
row_index = 1
i = 1
while i <= columns:
exec("a_{}{} = {}".format(row_index, i, float(input("Enter the value of the index a{}{} : ".format(row_index, i)))))
i += 1
if i == columns + 1:
row_index += 1
i = 1
if row_index == rows + 1:
break
while row_index <= rows + 1:
exec("row_{} = []".format(row_index))
row_index += 1
对于矩阵行的进一步计算,有必要将其元素添加到生成的表单列表中
row_1 = [a11, a12, ...an]
或者形式的字典
matrix = {row_1 = {a11 : 1, a12 : 2, a13 : 3},
row_2 = {a21 : 4, a22 : 5, a23 : 6},
...................................}
如何做到这一点?append()
方法不起作用。
python中是否有动态创建列表/字典并用数据填充它们的方法
任何有关该主题的信息都将有所帮助!
您可以直接尝试使用dictionary进行此操作。试试这段代码:
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
row_index = 1
i = 1
dict_matrix={}
while row_index <= rows :
i=1
row_name="row_"+str(row_index)
dict_matrix[row_name]={}
while i <= columns:
col_name="a"+str(row_index)+str(i)
value=int(input("Enter the value for "+col_name+" : "))
dict_matrix.get(row_name)[col_name]=value
i=i+1
row_index=row_index+1
print("out_of_loop")
print(dict_matrix)
这将为您提供一个结构如下的词典:
{'row_1': {'a11': 1, 'a12': 2}, 'row_2': {'a21': 3, 'a22': 4}, 'row_3': {'a31': 5, 'a32': 6}, 'row_4': {'a41': 7, 'a42': 8}}