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]]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With