简体   繁体   English

Python中map <int,vector <int >>的等价物是什么?

[英]What is the equivalent of map<int, vector<int> > in Python?

In C++ often do something like this: 在C ++中经常做这样的事情:

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

Where I then use it like this: 然后我在这里使用它:

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

If there was no entry in the map the code will insert a new empty vector and then append to it. 如果地图中没有条目,代码将插入一个新的空向量,然后附加到它。

In Python it would look like this: 在Python中它看起来像这样:

myIndex = {}

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

The try except is a bit ugly here. 尝试除了这里有点难看。 Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time? 有没有办法告诉字典在字典声明时遇到KeyError时要插入的对象类型?

You want to use: 你想用:

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

Standard Library defaultdict objects . 标准库defaultdict对象

Example usage from the Python documentation: 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])]

Something like this perhaps: 也许这样的东西:

myIndex = {}
for (someId,someVal) in collection:
    myIndex.setdefault(someId, []).append(someVal)

Just to complete the answer by Alastair: There is also the get equivalent of setdefault , which is called get (and not getdefault, as one might think): 只是为了完成Alastair的答案:还有相当于setdefaultget ,它叫做get (而不是getdefault,就像人们想象的那样):

myIndex = {}
someId = None
myList = myIndex.get(someId, []) # myList is [] now

From Python 2.5 and on you can get the behavior of setdefault or using defaultdict by implementing 从Python 2.5开始,你可以通过实现获得setdefault的行为或使用defaultdict

__missing__(k)

as in note 10 here . 如同在这里的注释10。

How about this? 这个怎么样? It may not be performance-optimal, but I think it's the "simplest thing that could possibly work". 它可能不是性能最佳的,但我认为它是“最可能有效的东西”。

myIndex = {}

for (someId,someVal) in collection:
   if someId not in myIndex:
       myIndex[someId] = []
   myIndex[someId].append(someVal)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM