python data structure: map<string, vector<int>>

浪子不回头ぞ 提交于 2019-12-12 03:46:42

问题


Sorry for asking this newbie question.

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

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.

Can I implement something similar in python? Note that I will have to plot with mathplot. So accessing the vector should be very easy.


回答1:


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)

This will print:

OrderedDict([('A1', [1, 2, 3]), ('B2', [2, 3])])

You can also add additional keys containing Lists like this:

m["B2"] = [2, 3, 5, 7]

You will then need to re-sort the OrderedDict.

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.




回答2:


Use a Dict :

m = {"A1" : [], "B3" : []}
m["A1"].append(1)
m["A1"].append(2)
m["B3"].append(3)

Note that you need to insert the key first in the dictionary, otherwise it would show KeyError. If you want to add a new key, suppose "A2" here, simply do :

m["A2"] = []

To sort the dictionary according to its keys, use an OrderedDict :

m = OrderedDict(sorted(m.items(), key = lambda t : t[0]))

One more thing, only non-mutable items such as strings, tuples, int, etc. are allowed as keys in a python dictionary, you can't have a dictionary with a list like [1,2,3] as one of the keys.



来源:https://stackoverflow.com/questions/40814582/python-data-structure-mapstring-vectorint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!