Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding and grouping same values, (float vectors) in nested lists

I have a list containing vectors (float x, y ,z values) and i'm trying group the same values together....

Here is a working example on a single list:

from collections import defaultdict

example_list = [1,5,1,4,2,5,5,4,5,7,2,1,7,9] 

d = defaultdict(list)

for item in example_list:
     d[item].append(item)

groupedlist = sorted(d[x] for x in d)

# Returns [[1, 1, 1], [2, 2], [4, 4], [5, 5, 5, 5], [7, 7], [9]]

I'm trying the achieve the same result for nested lists of 3D Vectors (X,Y,Z)...

example_vectorlist = [[1,2,4], [1,2,3], [3,4,3], [1,3,2], [5,6,7], [3,4,3], [5,6,7]]

# Desired output = [[1,2,4],[[1,2,3],[1,2,3]],[1,3,2],[[3,4,3], [3,4,3]],[[5,6,7], [5,6,7]]
like image 456
Siii Avatar asked May 24 '26 23:05

Siii


1 Answers

Just make the keys for your defaultdict into tuples:

from collections import defaultdict

example_list = [[1,2,4], [1,2,3], [3,4,3], [1,3,2], [5,7,1], [3,4,3], [5,6,1]]

d = defaultdict(list)

for item in example_list:
    d[tuple(item)].append(item)

groupedlist = sorted(d[x] for x in d)

The problem with just using the original "vectors" as keys to d is that lists aren't hashable; making tuples of them addresses this.

like image 127
Scott Hunter Avatar answered May 26 '26 13:05

Scott Hunter