Python数据结构

2024-09-29 17:16:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编程知之甚少,所以这是一个不知从何处寻找答案的案例。我希望创建如下数据结构:

vertexTopology = {vertexIndex: {clusterIndexes: intersection point}}

然而,实际的聚类索引是由聚类的索引组成的集合。所以我现在真正拥有的是:

^{pr2}$

如何创建与每个簇集及其顶点索引关联的唯一索引?比如:

vertexTopology = {5: {index associated with (1, 2, 3) AND vertex 5, intx_1}, 
                     {index associated with (2, 3, 4) AND vertex 5, intx_2},
                  6: {index associated with (1, 2, 3) AND vertex 6, intx_3}]
                  ...}

我不确定我要做的是最好的字典,所以任何建议都是非常欢迎的!在

下面是一个四点相交的图像,你可以想象一下我在处理什么。在

Four point intersection


Tags: and答案数据结构index编程with聚类案例
2条回答

Python中有一种东西叫做冻结集。这是一个你可以在字典中用作索引的集合。在

vertexTopology = {
    5: {
        (frozenset({1, 2, 3}), 5): intx_1,
        (frozenset({2, 3, 4}), 5): intx_2
    },
    6: {
        (frozenset({1, 2, 3}), 5): intx_3
    },
    ...
}

与集合不同,冻结集是不可变的。这就是为什么它们可以用作索引。在

使用hash()为簇集和顶点索引生成索引。 元组是散列类型。在

vertexTopology = {5: {hash(((1, 2, 3),5)): intx_1, 
                      hash(((2, 3, 4),5)): intx_2},
                  6: {hash(((1, 2, 3),6)): intx_3},
                  ...}

或者使用元组作为键

^{pr2}$

如果数据使用set,tuple()可以很容易地从set生成tuple

s = set([1, 2, 3])    # s is set
t = tuple(s)    # t is tuple

更新:

如果你想要其他哈希方法。str()是一个简单的解决方案。在

In [41]: import hashlib

In [42]: hashed = hashlib.sha512(str(((1, 2, 3), 4))).digest()

In [43]: hashed
Out[43]:
'mtE7\xf6N\xfc\xca\xc7\xb1\x0fA\x86|\xbe9j\xbb\xdf\xbaa\xd1\x05V\x84\xe8S\xfb\xe1\x16\xe05\x89,C\xa8\x94n\xae\x1e\n\xc0Y-)\xfa\xceG D\xe0C\xc9\xef\xb0\x8eCk\xe3`\xc2s\x97\xec'

相关问题 更多 >

    热门问题