I have a list of [row_index, column_index, value]. The row and column can be duplicated. I'd like to summing up this list to a matrix style list.
For instance,
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]]
On above example, value of 0 x 0
is 2
because list_of_list
contains [0,0,1], [0,0,1]
and 1 + 1 = 2
Build a dictionary that adds each sublist's last value to the value corresponding to a key of a tuple of the sublist's first two values:
>>> 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}
Find the size of the matrix:
>>> rows = max(item[0] for item in list_of_list)
>>> columns = max(item[1] for item in list_of_list)
Then you can create a matrix structure with a comprehension:
>>> structure = [[d.get((row, column), 0) for column in range(columns+1)] for row in range(rows+1)]
>>> structure
[[2, 0], [3, 4]]
A simple solution to this would be to first find out the shape of the output array by using max()
function , and then create an matrix of that shape with all 0
, and then keep summing the values from your list_of_list
to that output_matrix. Example -
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
Demo -
>>> 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]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.