How to combine arrays inside 2D array to a list if the first index value is the same?
Say for example, this 2D array:
[[0 0]
[0 3]
[0 4]
[1 1]
[2 2]
[3 0]
[3 3]
[3 4]
[4 0]
[4 3]
[4 4]]
How will I make it to something like this?
[[0, 0, 3, 4], [1 1], [2 2], [3 0 3 4], [4 0 3 4]]
When converting from numpy to list, I need it to be optimized as there are thousands of rows on my end.
Any suggestion is much appreciated. The end goal is I want the second index value to be combined together.
Also, take into consideration if ever the first index value is not in ascending order.
>Solution :
You can do it like that:
my_list = [
[0, 0],
[0, 3],
[0, 4],
[1, 1],
[2, 2],
[3, 0],
[3, 3],
[3, 4],
[4, 0],
[4, 3],
[4, 4]
]
from collections import defaultdict
d = defaultdict(list)
for i, j in my_list:
d[i].append(j)
combined = [[i]+l for i,l in d.items()]