Finding and grouping identical values ββ(float vectors) in nested lists
I have a list containing vectors (float x, y, z values) and I am trying to concatenate the same values ββtogether.
Here's a working example in one 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 am trying to 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]]
source to share
Just put the keys for defaultdict
in 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 using only the original "vectors" as keys to d
is that lists are not hashable; whereby their tuples address this.
source to share
Your desired output does not reflect what you have in the input, if you want to group the common sublists you can use itertools.groupby
assuming you want to sort the output with a dict and then sorting makes less sense than just creating groups from the sorted list using groupby:
from itertools import groupby
print([list(v) for _,v in groupby(sorted(example_vectorlist))])
Whichever source list for you outputs the same:
example_list = [1,5,1,4,2,5,5,4,5,7,2,1,7,9]
print([list(v) for _,v in groupby(sorted(example_list))])
[[1, 1, 1], [2, 2], [4, 4], [5, 5, 5, 5], [7, 7], [9]]
source to share