具有重复值的Python枚举 [英] Python Enums with duplicate values
问题描述
我无法使用其中某些属性具有相同值的Enum。我认为Enums是python的新手,所以我找不到关于此问题的其他参考。无论如何,假设我有以下
I'm having trouble working with an Enum where some attributes have the same value. I think Enums are so new to python that I can't find any other reference to this issue. In any case, let's say I have the following
class CardNumber(Enum):
ACE = 11
TWO = 2
THREE = 3
FOUR = 4
FIVE = 5
SIX = 6
SEVEN = 7
EIGHT = 8
NINE = 9
TEN = 10
JACK = 10
QUEEN = 10
KING = 10
很显然,这些是黑色插孔中的卡号及其对应的值。十个通王具有相同的价值。但是,如果我执行 print(CardNumber.QUEEN)
之类的操作,我会得到< CardNumber.TEN:10>
。更重要的是,如果我遍历这些,它只会遍历唯一值。
Clearly these are the card numbers and their corresponding values in black jack. The ten through king have the same value. But if I do something like print(CardNumber.QUEEN)
, I get back <CardNumber.TEN: 10>
. What's more, if I iterate over these, it simply iterates over unique values.
>>> for elem in CardNumber:
... print(elem)
CardNumber.ACE
CardNumber.TWO
CardNumber.THREE
CardNumber.FOUR
CardNumber.FIVE
CardNumber.SIX
CardNumber.SEVEN
CardNumber.EIGHT
CardNumber.NINE
CardNumber.TEN
如何解决这个问题?我希望CardNumber.QUEEN和CardNumber.TEN是唯一的,并且都出现在任何迭代中。我唯一能想到的就是为每个属性赋予第二个值,该值将充当不同的id,但这似乎是不合逻辑的。
How can I get around this issue? I want CardNumber.QUEEN and CardNumber.TEN to be unique, and both appear in any iteration. The only thing I could think of was to give each attribute a second value which would act as a distinct id, but that seems unpythonic.
推荐答案
是的,具有重复值的标签将变成第一个此类标签的别名。
Yes, labels with duplicate values are turned into aliases for the first such label.
您可以枚举 __ members __
属性,它是一个包含别名的有序词典:
You can enumerate over the __members__
attribute, it is an ordered dictionary with the aliases included:
>>> for name, value in CardNumber.__members__.items():
... print(name, value)
...
ACE CardNumber.ACE
TWO CardNumber.TWO
THREE CardNumber.THREE
FOUR CardNumber.FOUR
FIVE CardNumber.FIVE
SIX CardNumber.SIX
SEVEN CardNumber.SEVEN
EIGHT CardNumber.EIGHT
NINE CardNumber.NINE
TEN CardNumber.TEN
JACK CardNumber.TEN
QUEEN CardNumber.TEN
KING CardNumber.TEN
但是,如果必须具有唯一的标签和值对(而不是别名),则请 enum.Enum
是错误的方法;
However, if you must have label-and-value pairs that are unique (and not aliases), then enum.Enum
is the wrong approach here; it doesn't match the usecases for a card game.
在这种情况下,最好使用字典(考虑使用集合。 OrderedDict()
(如果订单也很重要)。
In that case it'll be better to use a dictionary (consider using collections.OrderedDict()
if order is important too).
这篇关于具有重复值的Python枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!