python 3.4: random.choice on Enum

耗尽温柔 提交于 2019-12-22 01:24:53

问题


I would like to use random.choice on an Enum.

I tried :

class Foo(Enum):
    a = 0
    b = 1
    c = 2
bar = random.choice(Foo)

But this code is not working, how can I do that ?


回答1:


An Enum is not a sequence, so you cannot pass it to random.choice(), which tries to pick an index between 0 and len(Foo). Like a dictionary, index access to an Enum instead expects enumeration names to be passed in, so Foo[<integer>] fails here with a KeyError.

You can cast it to a list first:

bar = random.choice(list(Foo))

This works because Enum does support iteration.

Demo:

>>> from enum import Enum
>>> import random
>>> class Foo(Enum):
...     a = 0
...     b = 1
...     c = 2
... 
>>> random.choice(list(Foo))
<Foo.a: 0>


来源:https://stackoverflow.com/questions/24243500/python-3-4-random-choice-on-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!