python数据结构:map< string,vector< int>>
很抱歉问这个新手问题.
Sorry for asking this newbie question.
在C ++中,我可以有这样的内容:
In C++, I can have something like this:
map<string, vector<int>> m
m["A1"].push_back(1);
m["A1"].push_back(2);
m["B3"].push_back(3); //etc
问题是我想用mathplot将其绘制出来.每个向量将根据其字符串值"A1","B3"等进行排序.
The thing is that I wanna plot it out with mathplot. Each vector will be sorting in according to their string value "A1", "B3", etc.
我可以在python中实现类似的东西吗? 请注意,我将必须使用mathplot进行绘图.因此访问向量应该非常容易.
Can I implement something similar in python? Note that I will have to plot with mathplot. So accessing the vector should be very easy.
在Python中,哈希表的等效项是Dict
(实际上,Dict
的大多数实现都是哈希表).为了确保跨实现的顺序,您将需要使用OrderedDict
. List
等效于向量.因此,您需要的是 OrderedDict
的 Lists
.
In Python, the equivalent of a hashmap is a Dict
(in fact, most implementation of Dict
are hashmaps). To ensure ordering across implementations, you will want to use an OrderedDict
. A List
is equivalent to a vector. Therefore, what you want is an OrderedDict
of Lists
.
from collections import OrderedDict
// Create the dictionary
d = {'A1': [1, 2], 'B2': [2, 3]}
// Order it by key
m = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
// Example of appending to one of the lists
m['A1'].append(3)
print(m)
这将打印:
OrderedDict([('A1', [1, 2, 3]), ('B2', [2, 3])])
您还可以添加其他包含列表的键,如下所示:
You can also add additional keys containing Lists like this:
m["B2"] = [2, 3, 5, 7]
然后您需要重新排序OrderedDict
.
一个小注释:Python中的Dicts
没有排序;它们恰好是在非常新的CPython 3版本中订购的,但这是一个实现细节.因此,OrderedDict
是此处最适用的数据结构,以确保您的代码可移植.我之所以这样说是因为许多人对CPython的这一功能感到非常兴奋,但是并不能保证它在任何地方都可以使用.
A minor note: Dicts
in Python aren't ordered; they happen to be ordered in very new versions of CPython 3, but that's an implementation detail. Therefore, OrderedDict
is the most applicable datastructure here, to ensure that your code is portable. I'm mentioning this because many people are very excited about this feature of CPython, but it's not guaranteed to work everywhere.