10

我需要一个具有数字索引的数据数组,但也需要一个人类可读的索引。我需要后者,因为数字索引将来可能会发生变化,并且我需要将数字索引作为固定长度套接字消息的一部分。

我的想象暗示了这样的事情:

ACTIONS = {
    (0, "ALIVE") : (1, 4, False),
    (2, "DEAD") : (2, 1, True)
}

>ACTIONS[0]
(1, 4, False)
>ACTIONS["DEAD"]
(2, 1, True)
4

4 回答 4

7

实现这一点的最简单方法是拥有两个字典:一个将索引映射到您的值,另一个将字符串键映射到相同的对象:

>> actions = {"alive": (1, 4, False), "dead": (2, 1, True)}
>> indexed_actions = {0: actions["alive"], 2: actions["dead"]}
>> actions["alive"]
(1, 4, False)
>> indexed_actions[0]
(1, 4, False)
于 2011-05-28T23:27:24.063 回答
6

使用 Python 2.7 的 collections.OrderedDict

In [23]: d = collections.OrderedDict([
   ....:   ("ALIVE", (1, 4, False)),
   ....:   ("DEAD", (2, 1, True)),
   ....: ])

In [25]: d["ALIVE"]
Out[25]: (1, 4, False)

In [26]: d.values()[0]
Out[26]: (1, 4, False)

In [27]: d.values()[1]
Out[27]: (2, 1, True)
于 2011-05-28T23:41:27.657 回答
1

如果您想为代码的可读性命名您的密钥,您可以执行以下操作:

ONE, TWO, THREE  = 1, 2, 3

ACTIONS = {
    ONE : value1,
    TWO : value2
}
于 2011-05-28T23:28:59.690 回答
1

命名元组很好:

>>> import collections
>>> MyTuple = collections.namedtuple('MyTuple', ('x','y','z'))
>>> t = MyTuple(1,2,3)
>>> t
MyTuple(x=1, y=2, z=3)
>>> t[0]
1
>>> t.x
1
>>> t.y
2
于 2011-05-29T00:31:32.113 回答