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

使用范围的Python多行人工枚举,python,enums,range,multiline,Python,Enums,Range,Multiline,我试图在Python中创建一个enum类型的类,但当您不得不这样做时,它会变得很长 VARIABLE1, VARIABLE2, VARIABLE3, VARIABLE3, VARIABLE4, VARIABLE5, VARIABLE6, VARIABLE7, VARIABLE8, ... , VARIABLE14 = range(14) 我试着像下面这样设置,但最终没有成功 VARIABLE1, VARIABLE2, VARIABLE3, ... VARIABLE14 = range(14)

我试图在Python中创建一个enum类型的类,但当您不得不这样做时,它会变得很长

VARIABLE1, VARIABLE2, VARIABLE3, VARIABLE3, VARIABLE4, VARIABLE5, VARIABLE6, VARIABLE7, VARIABLE8, ... , VARIABLE14 = range(14)
我试着像下面这样设置,但最终没有成功

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

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

哦,哇,我只是在变量周围加了括号,结果成功了

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

与手动键入VARIABLE1不同,VARIABLE2。。。您可以这样做:

>>> for x in range(1, 15):
        globals()['VARIABLE{0}'.format(x)] = x
做您想要的,而不需要额外的努力键入VARIABLE1。。。变量14。

使用新库和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>
>>SomeEnum.VARIABLE7

注意:
aenum
是由使用
namedtuple
的类似于
namedtuple
的枚举实现的作者编写的。此
enum
函数使用
namedtuple
创建一个类,并使用提供的参数实例化该类。参数是字符串、
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
[663]中的
:Color=enum('Color','black','white','red')
In[664]:颜色。黑色
Out[664]:0
In[665]:颜色为红色
Out[665]:2
在[666]中:#从1开始
在[667]中:Color=enum('Color',('black',1),'white','red')
In[668]:颜色。黑色
Out[668]:1
In[669]:颜色为红色
Out[669]:3
在[670]中:Animal=enum('Animal','cat','dog','lion',10','tiger'))
在[671]中:动物。狗
Out[671]:1
在[672]中:动物。老虎
Out[672]:11
在[673]中:Animal.tiger=12
---------------------------------------------------------------------------
AttributeError回溯(最近一次呼叫上次)
在()
---->1.老虎=12
AttributeError:无法设置属性

直线连接的明确方式是使用反斜杠字符:

VARIABLE1,\
VARIABLE2,\
VARIABLE3,\
...
VARIABLE14) = range(14)
隐式方法是用括号、方括号或大括号括起来:

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

通过学习一些关于范围函数的知识,您可以很快修复它。访问-了解更多详细信息。 我们看到这两个API是: 范围(停止) 范围(开始、停止[步进])

其中,它只返回特定范围内的数字列表,默认情况下,步骤为1

因此,您只需要明确地告诉python它们在同一行中,从而确保您的代码与您可以做到的一致,您可以通过在每行末尾添加“\”字符来做到这一点。 另外,如果用“[]”或“()”将它们标记为元组列表,python解释器将隐式地将其视为一行。使用列出的代码或自己进行实验,以获得更多信息。

将标识符(变量)构建为字符串,如
'variable{}。格式化(1)
,并制作一个genexp,它
生成由标识符和
('VARIABLE1',0)
等值组成的2元素
元组

>>> globals().update(('VARIABLE{}'.format(x+1), x) for x in range(14))
>>> VARIABLE1
0
>>> VARIABLE14
13
此genexp可用于馈送
dict
dict.update
。在OP的例子中,
dict
是由
globals()
返回的

>>> globals().update(('VARIABLE{}'.format(x+1), x) for x in range(14))
>>> VARIABLE1
0
>>> VARIABLE14
13
如果要分配的值是非整数
枚举
可以解决变量命名问题

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

我发现字典通常比枚举更合适,因为它们允许轻松地将整数映射到多个变量、函数等。例如,将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"

当然可以,或者你也可以用``行继续字符'来结束这些行。@bgporter你的意思是
\
?在注释中使用转义模式
```
而不是
`
编写。噢,是的,没错<代码>\
。我只是在使用VARIABLE1,VARIABLE2。。。作为一个例子,我实际拥有的肯定不能用于for循环。到目前为止最好的pythonic方法为什么要首先使用枚举?它解决了什么问题?它帮助我设置错误代码等。。。