子集上的 Python 枚举迭代

标签 python enums

我想遍历以下枚举的子集:

class Items(enum.Enum):
    item1 = 0
    item2 = 1
    item3 = 2
    item4 = 3
    item5 = 4
    item6 = 5
    item7 = 6
    item8 = 7

说我想:

for item in (Items.item1, Items.item2, Items.item3, Items.item4):
        print(item.value)

有捷径吗?或者我是否需要列出要迭代的每个项目?

最佳答案

使用 itertools.islice 您可以遍历 Enum 类的一部分

from enum import Enum
from itertools import islice

class Items(Enum):
    item1 = 0
    item2 = 1
    item3 = 2
    item4 = 3
    item5 = 4
    itm66 = 5
    item7 = 6
    item8 = 7

for i in islice(Items, 4):
    print(i.value)

# 0 
# 1 
# 2
# 3

关于子集上的 Python 枚举迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52957570/

相关文章:

jquery - 将枚举值传递到jQuery网格过滤器

c# - Swashbuckle - 在 swagger 文档中将字符串视为枚举

Python 3 : Getting two user inputs from a single line in a text file

java - 如何检测xml节点的数量?

python - 导入错误 : cannot import name 'password_reset'

java - 如何在 getter 和 setter 中使用枚举?

java - 如何要求泛型参数是实现接口(interface)的枚举?

python - 将两个数组的每一行连接成一个

python - Tensorflow模型输出大于1的概率值

c# - 在 C# 中实现枚举对象类型