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

标签 python sorting vector grouping

我有一个包含向量(浮点 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)

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

关于python - 在嵌套列表中查找和分组相同的值(浮点向量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31703548/

相关文章:

c++ - 多项式++ : How to increment p(x) by 1

C++ 查找 map 的第 N 个最高元素

python - 基本功能帮助-Python

Python 神经网络反向传播

python - 比较 PowerShell 和 Python 生成的 Windows PowerShell 中的两个 JSON 对象

python - 我怎样才能向量化这个 python 计数排序,使其绝对尽可能快?

c# - WPF 绑定(bind)到对象集合,按顺序存储在 C# 中的另一个集合中的 ID 排序

c - 将一维数组视为二维数组进行排序

c++ - 如何设置 Intellisense 以在 C++ 中显示自定义数据类型?

python - Peewee ORM - 从一个主数据库中的多个数据库复制数据