unordered_map<int, vector<float>> 在 Python 中等效

Cih*_*han 6 c++ python hashmap

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

[0] = {1.0, 1.0, 1.0, 1.0}
[1] = {0.5, 1.0}
Run Code Online (Sandbox Code Playgroud)

如果我用 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];
Run Code Online (Sandbox Code Playgroud)

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

osp*_*hiu 5

这种格式的字典- >{ (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
Run Code Online (Sandbox Code Playgroud)

  • @Cihan尝试[````collections.defaultdict(list)````](https://docs.python.org/3/library/collections.html#collections.defaultdict)。 (2认同)