Генерирование списков в циклt while и их наполнение динамически сгенерированными переменными (Python)

Создаю программу для решения СЛАУ с помощью матриц. Матрица имеет следующий вид:

а11 + а12 + ... + а1n = 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 существуют методы динамического создания списков/словарей и наполнения их данными?

Любая информация по теме будет полезной!


Ответы (1 шт):

Автор решения: Stanislav Volodarskiy

Не надо exec. Для хранения множества значений в одной переменной есть списки:

n = int(input("Enter the number of rows: "))
m = int(input("Enter the number of columns: "))

a = []
for i in range(n):
    a.append([])
    for j in range(m):
        v = float(input("Enter the value of the index a_{},{} : ".format(i + 1, j + 1)))
        a[i].append(v)

print(a)
$ python matrix.py
Enter the number of rows: 2
Enter the number of columns: 3
Enter the value of the index a_1,1 : 11
Enter the value of the index a_1,2 : 12
Enter the value of the index a_1,3 : 13
Enter the value of the index a_2,1 : 21 
Enter the value of the index a_2,2 : 22
Enter the value of the index a_2,3 : 23
[[11.0, 12.0, 13.0], [21.0, 22.0, 23.0]]
→ Ссылка