生成类似枚举的东西

时间:2014-08-15 03:06:53

标签: python

我想模仿枚举,但略有不同。有' N' N' N'列表中的不同实体。 ' N' N' N'根据数据而变化。我想分配其中的每一个' N'实体的值从1到N.对于某些实体,我想给它们相同的值。

例如, things = ['one', 'two', 'three', 'first', 'five']

我想分配:

one = 1
two = 2
three = 3
first = 1
five = 5

我如何以优雅的方式做到这一点?

3 个答案:

答案 0 :(得分:0)

你的意思是一个字典?

things = ['one', 'two', 'three', 'first', 'five']
result = {}
for index, thing in enumerate(things, start=1):
    result[thing] = index
result['first'] = 1
print result

然后result

{'three': 3, 'five': 5, 'two': 2, 'first': 1, 'one': 1}

答案 1 :(得分:0)

来自How can I represent an 'Enum' in Python?

我的方式如下。只需使用args定义典型的枚举,然后将任何特殊参数放在关键字参数中。

def enum(*args, **kwargs):
    enums = dict(zip(args, range(len(args))), **kwargs)
    return type('Enum', (), enums)
test = enum('a','b','c',first = 1, second = 2)
print test.a
print test.b
print test.c
print test.first
print test.second

收率:

0
1
2
1
2

此外,这将使用基于0的索引。如果您希望基数为1,请在示例中使用

range(1,len(args)+1))

而不是

range(len(args))

对我来说,如果你必须跳过值(比如四个)并且随机抛出特别指定的值(比如第一个),这似乎很麻烦。在这种情况下,我不认为你可以使用这个解决方案(或类似的东西)。相反,您可能必须找到任何特别指定的字符串并提供这些值,这将不那么优雅。

答案 2 :(得分:0)

使用Python函数enumerate。这就是它的用途。如在

 enumerate(things)

您可以将其转换为您想要的任何内容。喜欢:

dict(enumerate(things)) # =  {0: 'one', 1: 'two', 2: 'three', 3: 'first', 4: 'five'}
list(enumerate(things)) # = [(0, 'one'), (1, 'two'), (2, 'three'), (3, 'first'), (4, 'five')]
等等......

Pythonic的方法是在你需要的地方使用enumerate创建一个生成器。这可以避免生成额外的数据和消耗内存,尤其是当您的原始列表很长时。

相关问题