第二章:数据结构-enum:枚举类型-比较Enum

本文探讨了Python中枚举类型(Enum)的比较特性,包括同一性和相等性的区别,以及如何通过IntEnum实现枚举成员间的数值比较。通过实例展示了普通枚举无法直接排序,而IntEnum可以按值排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2.1.3 比较Enum
由于枚举成员是无序的,所以它们只支持按同一性和相等性进行比较。

import enum

class BugStatus(enum.Enum):

    new = 7
    incomplete = 6
    invalid = 5
    wont_fix = 4
    in_progress = 3
    fix_committed = 2
    fix_relessed = 1

actual_state = BugStatus.wont_fix
desired_state = BugStatus.fix_relessed

print('Equality:',
      actual_state == desired_state,
      actual_state == BugStatus.wont_fix)
print('Identity:',
      actual_state is desired_state,
      actual_state is BugStatus.wont_fix)
print('Ordered by value:')

try:
    print('\n'.join(' ' + s.name for s in sorted(BugStatus)))
except TypeError as err:
    print(' Cannot sort:{}'.format(err))

大于和小于比较符会产生TypeError异常。
运行结果:

Equality: False True
Identity: False True
Ordered by value:
Cannot sort:’<’ not supported between instances of ‘BugStatus’ and ‘BugStatus’

有些枚举中的成员要表现得更像数字,例如,要支持比较,对于这些枚举要使用IntEnum类。

import enum

class BugStatus(enum.IntEnum):

    new = 7
    incomplete = 6
    invalid = 5
    wont_fix = 4
    in_progress = 3
    fix_committed = 2
    fix_relesed = 1

print('Ordered by value:')
print('\n'.join(' ' + s.name for s in sorted(BugStatus)))

运行结果:

Ordered by value:
fix_relesed
fix_committed
in_progress
wont_fix
invalid
incomplete
new

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值