在python中将[row,column,value]的列表求和为2维列表

2024-05-20 20:45:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个[row\u index,column\u index,value]列表。行和列可以重复。我想把这个列表总结成一个矩阵式的列表。你知道吗

例如

list_of_list = [[0,0,1], [0,0,1], [1,0,3], [1,1,4]]
matrix_style_list = get_matrix_style_list(list_of_list)
print(matrix_style_list)

[[2, 0], [3, 4]]

在上面的例子中,0 x 0的值是2,因为list_of_list包含[0,0,1], [0,0,1]1 + 1 = 2


Tags: of列表getindexvaluestylecolumnmatrix
2条回答

解决这个问题的一个简单方法是,首先使用max()函数找出输出数组的形状,然后用所有0创建一个该形状的矩阵,然后继续将list_of_list中的值求和到该输出矩阵。示例-

list_of_list = [[0,0,1], [0,0,1], [1,0,3], [1,1,4]]
import operator
def get_matrix_style_list(lol):
    x_shape,y_shape = max(lol, key=operator.itemgetter(0,1))[0:2] 
    output_matrix = [[0 for _ in range(y_shape+1)] for _ in range(x_shape +1)]
    for x,y,val in lol:
        output_matrix[x][y] += val 
    return output_matrix

演示-

>>> list_of_list = [[0,0,1], [0,0,1], [1,0,3], [1,1,4]]
>>> import operator
>>> def get_matrix_style_list(lol):
...     x_shape,y_shape = max(lol, key=operator.itemget
...     output_matrix = [[0 for _ in range(y_shape+1)]
...     for x,y,val in lol:
...         output_matrix[x][y] += val
...     return output_matrix
...
>>> get_matrix_style_list(list_of_list)
[[2, 0], [3, 4]]

构建一个字典,将每个子列表的最后一个值添加到对应于子列表前两个值的元组的键的值中:

>>> list_of_list = [[0,0,1], [0,0,1], [1,0,3], [1,1,4]]
>>> d = {}
>>> for item in list_of_list:
...     *location, datum = item
...     location = tuple(location)
...     d[location] = d.get(location, 0) + datum
...
>>> d
{(1, 0): 3, (0, 0): 2, (1, 1): 4}

查找矩阵的大小:

>>> rows = max(item[0] for item in list_of_list)
>>> columns = max(item[1] for item in list_of_list)

然后您可以创建一个矩阵结构,并理解:

>>> structure = [[d.get((row, column), 0) for column in range(columns+1)] for row in range(rows+1)]
>>> structure
[[2, 0], [3, 4]]

相关问题 更多 >