【问题标题】:unordered_map<int, vector<float>> equivalent in PythonPython 中的 unordered_map<int, vector<float>> 等价物
【发布时间】:2016-12-19 20:37:38
【问题描述】:

我需要一个 Python 结构,它将整数索引映射到浮点数向量。我的数据是这样的:

[0] = {1.0, 1.0, 1.0, 1.0}
[1] = {0.5, 1.0}

如果我用 C++ 编写此代码,我将使用以下代码来定义/添加/访问,如下所示:

std::unordered_map<int, std::vector<float>> VertexWeights;
VertexWeights[0].push_back(0.0f);
vertexWeights[0].push_back(1.0f);
vertexWeights[13].push_back(0.5f);
std::cout <<vertexWeights[0][0];

在 Python 中 this 的等效结构是什么?

【问题讨论】:

    标签: python c++ hashmap


    【解决方案1】:

    这种格式的dictionary -> { (int) key : (list) value }

    d = {}  # Initialize empty dictionary.
    d[0] = [1.0, 1.0, 1.0, 1.0] # Place key 0 in d, and map this array to it.
    print d[0]
    d[1] = [0.5, 1.0]
    print d[1]
    >>> [1.0, 1.0, 1.0, 1.0]
    >>> [0.5, 1.0]
    print d[0][0]  # std::cout <<vertexWeights[0][0];
    >>> 1.0
    

    【讨论】:

    • 在 c++ 中,如果没有键可以说 d[15],那么它会自动创建。但是在 Pyhton 中我得到了关键错误。有没有办法克服这个?
    • 是的,C++ 和 python 在这方面的工作方式相同。更新了我的答案。 Python 的字典字面量本质上是一个无序映射。 @Cihan
    【解决方案2】:

    这样的字典和列表怎么样:

    >>> d = {0: [1.0, 1.0, 1.0, 1.0], 1: [0.5, 1.0]}
    >>> d[0]
    [1.0, 1.0, 1.0, 1.0]
    >>> d[1]
    [0.5, 1.0]
    >>> 
    

    键可以是整数,关联的值可以存储为列表。 Python 中的字典是一个哈希映射,复杂度被摊销了O(1)

    【讨论】:

      【解决方案3】:

      我会选择dict,其中整数作为键,list 作为项目,例如

      m = dict()
      m[0] = list()
      m[0].append(1.0)
      m[0].append(0.5)
      m[13] = list()
      m[13].append(13.0)
      

      如果不是太多数据

      【讨论】:

      • m[13] = list()应该在m[13].append(13.0)之前。
      猜你喜欢
      • 2010-09-24
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多