在python中将枚举转换为int

时间:2023-01-26 14:28:57

I have an enum Nationality:

我有一个enum国籍:

class Nationality:
        Poland='PL'
        Germany='DE'
        France='FR'

How can I convert this some enum to int in this or similar way:

如何以这种或类似的方式将此枚举转换为int:

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

but I don't have, and this way looks too big for python. I'm sure that there is something much simpler .

但我没有,这种方式看起来对于python来说太大了。我确信有一些更简单的东西。

6 个解决方案

#1


9  

There are better (and more "Pythonic") ways of doing what you want.

有更好的(和更多“Pythonic”)方式做你想要的。

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') 

Or use a dictionary along the lines of:

或者使用字典:

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 might also be useful, in your specific case, though it's probably overkill:

在你的特定情况下,一个namedtuple也可能有用,虽然它可能有点过分:

import collections
Nationalities = collections.namedtuple('Nationalities', 
                                       ['Poland', 'France', 'Germany'])
nat = Nationalities('PL', 'FR', 'DE')
print nat.Poland
print nat.index(nat.Germany)

#2


9  

Using either the enum34 backport or aenum1 you can create a specialized Enum:

使用enum34 backport或aenum1,您可以创建一个专门的枚举:

# using enum34
from enum import Enum

class Nationality(Enum):

    PL = 0, 'Poland'
    DE = 1, 'Germany'
    FR = 2, 'France'

    def __new__(cls, value, name):
        member = object.__new__(cls)
        member._value_ = value
        member.fullname = name
        return member

    def __int__(self):
        return self.value

and in use:

并在使用中:

>>> print(Nationality.PL)
Nationality.PL
>>> print(int(Nationality.PL))
0
>>> print(Nationality.PL.fullname)
'Poland'

The above is more easily written using aenum1:

使用aenum1更容易编写以上内容:

# using aenum
from aenum import Enum, MultiValue

class Nationality(Enum):
    _init_ = 'value fullname'
    _settings_ = MultiValue

    PL = 0, 'Poland'
    DE = 1, 'Germany'
    FR = 2, 'France'

    def __int__(self):
        return self.value

which has the added functionality of:

它具有以下附加功能:

>>> Nationality('Poland')
<Nationality.PL: 0>

1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

1披露:我是Python stdlib Enum,enum34 backport和Advanced Enumeration(aenum)库的作者。

#3


5  

You can't. Python does not store the order of class elements and dir() will return them in any order.

你不能。 Python不存储类元素的顺序,dir()将以任何顺序返回它们。

Seeing from your comment that you really do require a mapping from strings to integers, you should in fact do exactly that:

从你的评论中看到你确实需要从字符串到整数的映射,你实际上应该这样做:

code_lookup = {
    'PL': ("Poland", 0), 
    'DE': ("Germany", 1), 
    'FR': ("France", 2), 
    ... 
}

#4


4  

Why don't you just define the values as numbers instead of strings:

为什么不直接将值定义为数字而不是字符串:

class Nationality:
    POLAND = 0
    GERMANY = 1
    FRANCE = 2

If you need to access the two-letter names, you can simply provide a table that maps them. (Or a dictionary that maps the other way, etc.)

如果您需要访问两个字母的名称,您只需提供一个映射它们的表。 (或者用其他方式映射的字典等)

#5


4  

I have seen something like:

我见过类似的东西:

PL, FR, DE = range(3)

Wrap it in a class and viola, you have a namespace for the enumeration.

将它包装在类和中提琴中,您有枚举的命名空间。

#6


0  

please use IntEnum

请使用IntEnum

from enum import IntEnum

class loggertype(IntEnum):
    Info = 0
    Warning = 1
    Error = 2
    Fetal = 3

int(loggertype.Info)
0

#1


9  

There are better (and more "Pythonic") ways of doing what you want.

有更好的(和更多“Pythonic”)方式做你想要的。

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') 

Or use a dictionary along the lines of:

或者使用字典:

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 might also be useful, in your specific case, though it's probably overkill:

在你的特定情况下,一个namedtuple也可能有用,虽然它可能有点过分:

import collections
Nationalities = collections.namedtuple('Nationalities', 
                                       ['Poland', 'France', 'Germany'])
nat = Nationalities('PL', 'FR', 'DE')
print nat.Poland
print nat.index(nat.Germany)

#2


9  

Using either the enum34 backport or aenum1 you can create a specialized Enum:

使用enum34 backport或aenum1,您可以创建一个专门的枚举:

# using enum34
from enum import Enum

class Nationality(Enum):

    PL = 0, 'Poland'
    DE = 1, 'Germany'
    FR = 2, 'France'

    def __new__(cls, value, name):
        member = object.__new__(cls)
        member._value_ = value
        member.fullname = name
        return member

    def __int__(self):
        return self.value

and in use:

并在使用中:

>>> print(Nationality.PL)
Nationality.PL
>>> print(int(Nationality.PL))
0
>>> print(Nationality.PL.fullname)
'Poland'

The above is more easily written using aenum1:

使用aenum1更容易编写以上内容:

# using aenum
from aenum import Enum, MultiValue

class Nationality(Enum):
    _init_ = 'value fullname'
    _settings_ = MultiValue

    PL = 0, 'Poland'
    DE = 1, 'Germany'
    FR = 2, 'France'

    def __int__(self):
        return self.value

which has the added functionality of:

它具有以下附加功能:

>>> Nationality('Poland')
<Nationality.PL: 0>

1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

1披露:我是Python stdlib Enum,enum34 backport和Advanced Enumeration(aenum)库的作者。

#3


5  

You can't. Python does not store the order of class elements and dir() will return them in any order.

你不能。 Python不存储类元素的顺序,dir()将以任何顺序返回它们。

Seeing from your comment that you really do require a mapping from strings to integers, you should in fact do exactly that:

从你的评论中看到你确实需要从字符串到整数的映射,你实际上应该这样做:

code_lookup = {
    'PL': ("Poland", 0), 
    'DE': ("Germany", 1), 
    'FR': ("France", 2), 
    ... 
}

#4


4  

Why don't you just define the values as numbers instead of strings:

为什么不直接将值定义为数字而不是字符串:

class Nationality:
    POLAND = 0
    GERMANY = 1
    FRANCE = 2

If you need to access the two-letter names, you can simply provide a table that maps them. (Or a dictionary that maps the other way, etc.)

如果您需要访问两个字母的名称,您只需提供一个映射它们的表。 (或者用其他方式映射的字典等)

#5


4  

I have seen something like:

我见过类似的东西:

PL, FR, DE = range(3)

Wrap it in a class and viola, you have a namespace for the enumeration.

将它包装在类和中提琴中,您有枚举的命名空间。

#6


0  

please use IntEnum

请使用IntEnum

from enum import IntEnum

class loggertype(IntEnum):
    Info = 0
    Warning = 1
    Error = 2
    Fetal = 3

int(loggertype.Info)
0