python - Python 中的 map<int, vector<int>> 是什么?

标签 python dictionary

在 C++ 中经常做这样的事情:

typedef map<int, vector<int> > MyIndexType;

然后我会像这样使用它:

MyIndexType myIndex;
for( ... some loop ...)
{
  myIndex[someId].push_back(someVal);
}

如果映射中没有条目,代码将插入一个新的空向量,然后附加到它。

在 Python 中它看起来像这样:

myIndex = {}

for (someId,someVal) in collection:
   try:
      myIndex[someId].append(someVal)
   except KeyError:
      myIndex[someId] = [someVal]

这里的 try except 有点难看。在字典声明时遇到 KeyError 时,有没有办法告诉字典要插入的对象类型?

最佳答案

你想使用:

from collections import defaultdict
myIndex = defaultdict(list)
myIndex[someId].append(someVal)

标准库 defaultdict objects .

Python 文档中的示例用法:

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
        d[k].append(v)

>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

关于python - Python 中的 map<int, vector<int>> 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/324643/

相关文章:

python - 按新的日期范围重新索引数据框

python - 使用 REST API python 将页面 blob 上传到 azure

python - 函数内的字典值和列表值

c# - Gridview Item has already been added 错误

ios - 快速调用中的额外参数

python - 如何修复错误 : module 'discord' has no attribute 'Bot'

Python变量名称.错误

python - 使用类而不是列表 python

python - 通过更改键对 Python 字典进行排序,现在当我尝试迭代它时,它会迭代更改后的键

java - 如何使用可选参数从 HashMap 中检索值