Python 使用范围的多行人工枚举

发布于 2024-10-08 23:38:36 字数 344 浏览 0 评论 0原文

我正在尝试在Python中创建一个枚举类型的类,但是当你必须这样做时它会变得很长

VARIABLE1, VARIABLE2, VARIABLE3, VARIABLE3, VARIABLE4, VARIABLE5, VARIABLE6, VARIABLE7, VARIABLE8, ... , VARIABLE14 = range(14)

,并且我尝试像下面这样设置它,但最终没有工作。

VARIABLE1,
VARIABLE2,
VARIABLE3,
...
VARIABLE14 = range(14)

我如何以最简单的方式实现这一点?

I am trying to make an enum-type class in Python but it gets so lengthly when you have to do

VARIABLE1, VARIABLE2, VARIABLE3, VARIABLE3, VARIABLE4, VARIABLE5, VARIABLE6, VARIABLE7, VARIABLE8, ... , VARIABLE14 = range(14)

and I've tried to set it up like the following, but ended up not working.

VARIABLE1,
VARIABLE2,
VARIABLE3,
...
VARIABLE14 = range(14)

How would I accomplish this in the simplest way possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

美人迟暮 2024-10-15 23:38:36

哦,哇,我刚刚在变量周围添加了括号,它就起作用了

(VARIABLE1,
VARIABLE2,
VARIABLE3,
...
VARIABLE14) = range(14)

Oh, wow I just added brackets around the variables and it worked

(VARIABLE1,
VARIABLE2,
VARIABLE3,
...
VARIABLE14) = range(14)
面如桃花 2024-10-15 23:38:36

您可以执行以下操作,而不是手动键入 VARIABLE1、VARIABLE2 ...:

>>> for x in range(1, 15):
        globals()['VARIABLE{0}'.format(x)] = x

执行您想要的操作,无需额外输入 VARIABLE1 ... VARIABLE 14。

Instead of manually typing VARIABLE1, VARIABLE2 ... you can do this:

>>> for x in range(1, 15):
        globals()['VARIABLE{0}'.format(x)] = x

Does what you want, without the extra effort of typing VARIABLE1 ... VARIABLE 14.

何处潇湘 2024-10-15 23:38:36

行连接的显式方式是使用反斜杠字符:

VARIABLE1,\
VARIABLE2,\
VARIABLE3,\
...
VARIABLE14) = range(14)

而隐式方式是用括号、方括号或大括号括起来:

[VARIABLE1,
 VARIABLE2,
 VARIABLE3,
 ...
 VARIABLE14] = range(14)

The explicit way of line joining is to use backslash characters:

VARIABLE1,\
VARIABLE2,\
VARIABLE3,\
...
VARIABLE14) = range(14)

and the implicit way is to enclose with parentheses, square brackets or curly braces:

[VARIABLE1,
 VARIABLE2,
 VARIABLE3,
 ...
 VARIABLE14] = range(14)
你对谁都笑 2024-10-15 23:38:36

使用新的 aenum 库和 Python 3 你可以这样做:

from aenum import Enum

class SomeEnum(Enum, start=0):
    VARIABLE1
    VARIABLE2
    VARIABLE3
    VARIABLE4
    VARIABLE5
    VARIABLE6
    VARIABLE7
    VARIABLE8
    VARIABLE9
    VARIABLE10
    VARIABLE11
    VARIABLE12
    VARIABLE13
    VARIABLE14

并且使用中看起来像:

>>> SomeEnum.VARIABLE7
<SomeEnum.VARIABLE7: 6>

注意:< code>aenum 由 enum34 的作者编写

Using the new aenum library and Python 3 you can do:

from aenum import Enum

class SomeEnum(Enum, start=0):
    VARIABLE1
    VARIABLE2
    VARIABLE3
    VARIABLE4
    VARIABLE5
    VARIABLE6
    VARIABLE7
    VARIABLE8
    VARIABLE9
    VARIABLE10
    VARIABLE11
    VARIABLE12
    VARIABLE13
    VARIABLE14

and in use looks like:

>>> SomeEnum.VARIABLE7
<SomeEnum.VARIABLE7: 6>

Note: aenum is written by the author of enum34

骷髅 2024-10-15 23:38:36

类似于使用 namedtuplenamedtuple 的枚举实现。此 enum 函数使用 namedtuple 创建一个类,并使用提供的参数实例化该类。参数是字符串、元组或列表。参数的元组或列表形式用于向常量提供值,从而重置值序列。默认情况下,常量的值从零开始。

def enum(name, *args):
    from collections import namedtuple

    kwargs = {}
    start = 0
    for arg in args:
        if isinstance(arg, basestring):
            kwargs[arg] = start
            start += 1
        elif isinstance(arg, (tuple, list)):
            if len(arg) != 2:
                raise ValueError('"{}" must be a two element tuple or list'.format(arg))
            attr, start = arg
            if isinstance(attr, basestring):
                if isinstance(start, int):
                    kwargs[attr] = start
                    start += 1
                else:
                    raise TypeError('second element of "{}" must be of type "int"'.format(arg))
            else:
                raise TypeError('first element of "{}" must be sub type of "basestring"'.format(arg))
        else:
            raise TypeError('Argument "{}" must be either sub type of "basestring", "tuple" or "list" of ("basestring", "int")'.format(arg))

    if isinstance(name, basestring):
        return namedtuple(name, kwargs.keys())(**kwargs)
    raise TypeError('Argument "{}" must be an instance of "basestring"'.format(name))

用法;

In [663]: Color = enum('Color', 'black', 'white', 'red')

In [664]: Color.black
Out[664]: 0

In [665]: Color.red
Out[665]: 2

In [666]: #To start from 1

In [667]: Color = enum('Color', ('black',1), 'white', 'red')

In [668]: Color.black
Out[668]: 1

In [669]: Color.red
Out[669]: 3

In [670]: Animal = enum('Animal','cat', 'dog', ['lion',10],'tiger')

In [671]: Animal.dog
Out[671]: 1

In [672]: Animal.tiger
Out[672]: 11

In [673]: Animal.tiger = 12
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-673-8823b3c2482c> in <module>()
----> 1 Animal.tiger = 12

AttributeError: can't set attribute

An enum implementation similar to namedtuple using namedtuple. This enum function creates a class with namedtuple and instantiates the class with supplied arguments. Arguments are strings, tuple or list. The tuple or list form of arguments are used to supply a value to the constants thus resetting value sequence. By default, constants are valued starting from zero.

def enum(name, *args):
    from collections import namedtuple

    kwargs = {}
    start = 0
    for arg in args:
        if isinstance(arg, basestring):
            kwargs[arg] = start
            start += 1
        elif isinstance(arg, (tuple, list)):
            if len(arg) != 2:
                raise ValueError('"{}" must be a two element tuple or list'.format(arg))
            attr, start = arg
            if isinstance(attr, basestring):
                if isinstance(start, int):
                    kwargs[attr] = start
                    start += 1
                else:
                    raise TypeError('second element of "{}" must be of type "int"'.format(arg))
            else:
                raise TypeError('first element of "{}" must be sub type of "basestring"'.format(arg))
        else:
            raise TypeError('Argument "{}" must be either sub type of "basestring", "tuple" or "list" of ("basestring", "int")'.format(arg))

    if isinstance(name, basestring):
        return namedtuple(name, kwargs.keys())(**kwargs)
    raise TypeError('Argument "{}" must be an instance of "basestring"'.format(name))

Usage;

In [663]: Color = enum('Color', 'black', 'white', 'red')

In [664]: Color.black
Out[664]: 0

In [665]: Color.red
Out[665]: 2

In [666]: #To start from 1

In [667]: Color = enum('Color', ('black',1), 'white', 'red')

In [668]: Color.black
Out[668]: 1

In [669]: Color.red
Out[669]: 3

In [670]: Animal = enum('Animal','cat', 'dog', ['lion',10],'tiger')

In [671]: Animal.dog
Out[671]: 1

In [672]: Animal.tiger
Out[672]: 11

In [673]: Animal.tiger = 12
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-673-8823b3c2482c> in <module>()
----> 1 Animal.tiger = 12

AttributeError: can't set attribute
若水微香 2024-10-15 23:38:36

通过了解一些关于范围函数的知识,您可以立即修复它。请访问文档了解更多详细信息。
我们看到 2 个 api 是:
范围(停止)
range(start, stop[, step])

它只返回该特定范围内的数字列表,步长默认为 1。

因此,您只需要确保您的代码符合您可以通过显式告诉 python 它们位于同一行中来执行的操作,您可以通过在每行末尾添加 '\' 字符来执行此操作。
另外,如果你用“[]”或“()”将它们括起来,将它们标记为元组列表,Python解释器将隐式地将其视为一行。使用列出的代码或自己进行实验以获得更多窍门。

By learning a bit about range function you can fix it in no time. Visit - documentation for more details.
We see that the 2 apis(s) are:
range(stop)
range(start, stop[, step])

Where it just returns a list of numbers in that particular range with step which is 1 by default.

Hence you just need to make sure that your code is compliant with that which you can do by explicitly telling python that they are the in the same line which you can do by adding '\' character at the end of every line.
Also if you enclose them by '[]' or '()' marking them as list of tuple, the python interpreter will implicitly treat it as a one line. Use the codes listed or experiment yourself to get more hang of it.

情魔剑神 2024-10-15 23:38:36

将标识符(变量)构建为 'VARIABLE{}'.format(1) 等字符串,并创建一个 yield 2 元素元组 的 genexp > 由标识符和值组成,如 ('VARIABLE1', 0)

此 genexp 可用于提供 dictdict.update。在OP的例子中,dict是由globals()返回的。

>>> globals().update(('VARIABLE{}'.format(x+1), x) for x in range(14))
>>> VARIABLE1
0
>>> VARIABLE14
13

如果要赋值的值是非整数enumerate可以解决变量命名的问题。

>>> globals().update(('VARIABLE{}'.format(i), x) for i, x in enumerate('abcdefghijklmn',1))
>>> VARIABLE1
'a'
>>> VARIABLE14
'n'

Build the identifiers (variable) as strings like 'VARIABLE{}'.format(1) and make a genexp which yields 2-element tuples consisting of the identifier and the value like ('VARIABLE1', 0).

This genexp can be used to feed a dict or dict.update. In The OP's case the dict is the one returned by globals().

>>> globals().update(('VARIABLE{}'.format(x+1), x) for x in range(14))
>>> VARIABLE1
0
>>> VARIABLE14
13

If the values to be assigned are non-integers enumerate can solve the problem of variable naming.

>>> globals().update(('VARIABLE{}'.format(i), x) for i, x in enumerate('abcdefghijklmn',1))
>>> VARIABLE1
'a'
>>> VARIABLE14
'n'
未央 2024-10-15 23:38:36

我发现字典通常比枚举更合适,因为它们可以轻松地将整数映射到多个变量、函数等。例如,将 in 分配给函数和字符串:

import numpy as np,

CC = [(np.sin, "Taking the sine"),
      (np.cos, "Taking the cosine"),
      (np.tan, "Taking the tangens")]
dCC = dict(enumerate(CC, start=1))  # built the enumerated dictionary


def calc(n, x):
    """ Perform operation on `x` defined by number `n` """
    f, s = dCC[n]  # map number to function and string
    y = f(x)
    print(s + " from %g results in %g" % (x, y))
    return y

y = calc(2, np.pi)  # prints: "Taking the tangens from 3.14159 results in -1"

I find dictionaries often to be more suitable than enums, because they allow to easily map integers to more than one variable, function etc. For example assigning an in to a function and string:

import numpy as np,

CC = [(np.sin, "Taking the sine"),
      (np.cos, "Taking the cosine"),
      (np.tan, "Taking the tangens")]
dCC = dict(enumerate(CC, start=1))  # built the enumerated dictionary


def calc(n, x):
    """ Perform operation on `x` defined by number `n` """
    f, s = dCC[n]  # map number to function and string
    y = f(x)
    print(s + " from %g results in %g" % (x, y))
    return y

y = calc(2, np.pi)  # prints: "Taking the tangens from 3.14159 results in -1"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文