[英]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的答案:还有相当于setdefault的get ,它叫做get (而不是getdefault,就像人们想象的那样):
myIndex = {}
someId = None
myList = myIndex.get(someId, []) # myList is [] now
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.