python 将列表转换为矩阵并获取值

python convert list to matrix and get value

我对 python 很陌生。我在嵌套列表中有 16 个 1 和 0 的列表。

list([name_of_matrix],[1234567812345678], [another_name],[1234....])

列表中的每个数字项 [12345678....] 代表一个 4x4 矩阵,如下所示:

1234
5678
1234
5678

我的目标是通过 [row, col]. 访问数字,例如 [2,3] 是第 2 行,第 3 列,即 7。我应该如何转换列表以实现此目的?提前谢谢了。

你可以使用字典:

my_matrix_collection = {
    'name_one' : np.array([[1,2,3,4],[5,6,7,8],[1,2,3,4],[5,6,7,8]]),
    'name_two' : np.array([[10,20,30,40],[50,60,70,80],[10,20,30,40],[50,60,70,80]])
}

现在您可以访问特定矩阵的矩阵元素,例如:

my_matrix_collection['name_one'][2,3] #output 4

要从您的列表中获取字典 my_matrix_collection(我们称之为 my_list),请执行以下操作:

my_matrix_collection = {} #create an empty dictionary
for i in range(len(my_list)//2):
    my_matrix_collection[my_list[2*i]] = np.array(list(my_list[2*i+1]),dtype=float)).reshape((4,4)) #populate the empty dictionary

您只需将列表作为字符串传递给列表方法,并从该列表中创建一个浮点类型的 numpy 数组:

my_matrix = np.array(list('1234567812345678'),dtype=float).reshape((4,4))

现在您可以像这样访问它:

my_matrix[2,3] #output 4

首先,您应该将嵌套的 list 分解为 dict,其中键是表示名称的字符串,值是整数:

nested_list = [['first'], [1234567812345678], ['second'], [1234432109877890]]
raw_dict = {k[0]: v[0] for k, v in zip(nested_list[::2], nested_list[1::2])}

现在,我们想把每一个16位整数都变成更能代表矩阵的东西。 numpy 是一种方法,但让我们暂时坚持基本的 Python。

观察到如果我们将每个整数转换为字符串,每个 4 个字符的块将代表矩阵的一行。据此:

def to_matrix(i):
    string = str(i)
    return [[int(element) for element in string[i:i + 4]] for i in range(0, 16, 4)]

matrix_dict = {k: to_matrix(v) for k, v in raw_dict.items()}

现在,我们的 dict 具有嵌套的值 lists,代表矩阵:

print(matrix_dict)

输出:

{'first': [[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4], [5, 6, 7, 8]], 'second': [[1, 2, 3, 4], [4, 3, 2, 1], [0, 9, 8, 7], [7, 8, 9, 0]]}

我们可以通过链式索引访问任意元素:

print(matrix_dict['first'][3][2])

输出:

7

编辑:如果我们不想区分列表,那么我们可以这样做:

matrices = [to_matrix(element[0]) for element in nested_list if isinstance(element[0], int)]