开发者

What is a flexible, hybrid python collection object?

As a way to get used to python, I am trying to translate some of my code to pyt开发者_运维百科hon from Autohotkey_L.

I am immediately running into tons of choices for collection objects.

Can you help me figure out a built in type or a 3rd party contributed type that has as much as possible, the functionality of the AutoHotkey_L object type and its methods.

AutoHotkey_L Objects have features of a python dict, list, and a class instance.

I understand that there are tradeoffs for space and speed, but I am just interested in functionality rather than optimization issues.


Don't write Python as <another-language>. Write Python as Python.

The data structure should be chosen just to have the minimal ability you need to use.

  • list — an ordered sequence of elements, with 1 flexible end.
  • collections.deque — an ordered sequence of elements, with 2 flexible ends (e.g. a queue).
  • set / frozenset — an unordered sequence of unique elements.
  • collections.Counter — an unordered sequence of non-unique elements.
  • dict — an unordered key-value relationship.
  • collections.OrderedDict — an ordered key-value relationship.
  • bytes / bytearray — a list of bytes.
  • array.array — a homogeneous list of primitive types.

Looking at the interface of Object,

  • dict would be the most suitable for finding a value by key
  • collections.OrderedDict would be the most suitable for the push/pop stuff.

when you need MinIndex / MaxIndex, where a sorted key-value relationship (e.g. red black tree) is required. There's no such type in the standard library, but there are 3rd party implementations.


It would be impossible to recommend a particular class without knowing how you intend on using it. If you are using this particular object as an ordered sequence where elements can be repeated, then you should use a list; if you are looking up values by their key, then use a dictionary. You will get very different algorithmic runtime complexity with the different data types. It really does not take that much time to determine when to use which type.... I suggest you give it some further consideration.

If you really can't decide, though, here is a possibility:

class AutoHotKeyObject(object):
    def __init__(self):
        self.list_value = []
        self.dict_value = {}
    def getDict(self):
        return self.dict_value
    def getList(self):
        return self.list_value

With the above, you could use both the list and dictionary features, like so:

obj = AutoHotKeyObject()
obj.getList().append(1)
obj.getList().append(2)
obj.getList().append(3)
print obj.getList() # Prints [1, 2, 3]
obj.getDict()['a'] = 1
obj.getDict()['b'] = 2
print obj.getDict() # Prints {'a':1, 'b':2}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜