问题 使用范围的Python多线人工枚举


我正在尝试在Python中创建一个枚举类,但是当你不得不这样做时,它会变得如此长

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

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

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

我将如何以最简单的方式实现这一目标?


3247
2017-12-22 18:32


起源

为什么首先要打扰枚举?它解决了什么问题? - S.Lott
它可以帮助我设置错误代码等... - MetaDark


答案:


哦,哇我只是在变量周围添加括号并且它有效

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

8
2017-12-22 18:34



当然,或者你可以用``line continuation character结束每一行。 - bgporter
@bgporter你的意思是 \?写在带有逃避模式的评论中 ``\`` 代替 `\`。 - tmthydvnprt
我希望有一个评论降价预览... - tmthydvnprt
哎呀,是的,确切地说。 \。 - bgporter


而不是手动键入VARIABLE1,VARIABLE2 ...您可以这样做:

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

你想要什么,没有额外的努力键入VARIABLE1 ... VARIABLE 14。


2
2017-12-22 18:39



我只是使用VARIABLE1,VARIABLE2 ......作为一个例子,我实际拥有的东西肯定不适用于这个for循环。 - MetaDark
到目前为止最好的pythonic方法 - mvelay


使用新的 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>

注意: aenum 由作者撰写 enum34


2
2018-03-12 23:24





枚举实现类似于 namedtuple 运用 namedtuple。这个 enum 函数创建一个类 namedtuple 并使用提供的参数实例化该类。参数是字符串, tuple 要么 list。该 tuple 要么 list 参数形式用于为常量提供值,从而重置值序列。默认情况下,常量从零开始计算。

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

2
2018-03-16 10:32





行连接的明确方法是使用反斜杠字符:

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

隐含的方法是用括号,方括号或花括号括起来:

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

1
2018-03-18 15:43





通过了解一下范围功能,您可以立即修复它。访问 - 文件 更多细节。 我们看到2个apis是: 范围(停止) 范围(开始,停止[,步骤])

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

因此,您只需要确保您的代码符合您可以通过明确告诉python他们是在同一行中您可以通过在每行的末尾添加'\'字符来实现的代码。 此外,如果您通过'[]'或'(''将它们标记为元组列表来封装它们,python解释器将隐式将其视为一行。使用列出的代码或自己试验以获得更多信息。


1
2018-03-19 06:48





将标识符(变量)构建为字符串 'VARIABLE{}'.format(1) 并制作一个genexp yields 2元素 tuples由标识符和值组成 ('VARIABLE1', 0)

这个genexp可以用来喂养a dict 要么 dict.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'

0
2018-03-19 14:07





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

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"

0
2018-03-19 16:20