在python中将枚举转换为int [英] Convert enum to int in python
问题描述
我有一个列举的国籍:
class Nationality:
Poland='PL'
Germany='DE'
France='FR'
如何将某些枚举转换为int以这种或类似的方式:
How can I convert this some enum to int in this or similar way:
position_of_enum = int(Nationality.Poland) # here I want to get 0
我知道我可以通过以下方式进行编码:
I know that I can do it if I had code by:
counter=0
for member in dir(Nationality):
if getattr(Nationality, member) == code:
lookFor = member
counter += 1
return counter
但我没有,并且这种方式对于python来说太大了。我肯定有简单得多的东西。
but I don't have, and this way looks too big for python. I'm sure that there is something much simpler .
推荐答案
有更好的(以及更多的 Pythonic)方法
There are better (and more "Pythonic") ways of doing what you want.
可以使用元组(或列出是否需要修改)来保存订单:
Either use a tuple (or list if it needs to be modified), where the order will be preserved:
code_lookup = ('PL', 'DE', 'FR')
return code_lookup.index('PL')
或使用以下字典:
code_lookup = {'PL':0, 'FR':2, 'DE':3}
return code_lookup['PL']
在我看来,后者更可取,因为它更具可读性和明确性。
The latter is preferable, in my opinion, as it's more readable and explicit.
A namedtuple
在您的特定情况下可能也很有用,尽管它可能会过大:
A namedtuple
might also be useful, in your specific case, though it's probably overkill:
import collections
Nationalities = collections.namedtuple('Nationalities',
['Poland', 'France', 'Germany'])
nat = Nationalities('PL', 'FR', 'DE')
print nat.Poland
print nat.index(nat.Germany)
这篇关于在python中将枚举转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!