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

问题描述 投票:1回答:3

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

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

列表中的每个数字项[12345678....]表示像这样的4x4矩阵:

1234
5678
1234
5678

我的目标是通过[row, col].访问一个数字例如[2,3]将是第2行,col3,这是7.如何转换列表来实现这一目标?提前谢谢了。

python list matrix nested nested-lists
3个回答
1
投票

首先,您应该将嵌套的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)]

0
投票

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

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

现在您可以访问它:

my_matrix[2,3] #output 4

0
投票

你可以使用字典:

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
© www.soinside.com 2019 - 2024. All rights reserved.