在嵌套列表中查找和分组相同的值(浮点向量)

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

我有一个包含向量(浮点 x、y、z 值)的列表,我正在尝试将相同的值组合在一起....

这是一个关于单个列表的工作示例:

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]]

我正在尝试为 3D 向量 (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]]

只需将 defaultdict 的键放入元组中:

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)

仅使用原始 "vectors" 作为 d 的键的问题是列表不可散列;制作它们的元组解决了这个问题。

你想要的输出并不能反映你的输入,如果你想对常见的子列表进行分组,你可以使用 itertools.groupby,考虑到你想使用字典对输出进行排序,然后排序比仅仅创建更有意义使用 groupby 对排序列表进行分组:

from itertools import groupby

print([list(v) for _,v in groupby(sorted(example_vectorlist))])

你的原始列表输出相同:

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]]

不使用 defaultdict:

example_vectorlist = [[1,2,4], [1,2,3], [3,4,3], [1,3,2], [5,7,1],[3,4,3], [5,6,1]]
d = {}
for el in example_vectorlist:
    try:
        d[tuple(el)].append(el)
    except KeyError:
        d[tuple(el)] = [el]
print d.values()