← 返回题库
初级

实现枚举值验证

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
def solve():
    from pyodide.http import open_url
    from io import StringIO
    raw_requests_csv = open_url("https://data.zuihe.com/dbd/ms-shop/state_01/raw_requests.csv").read()
    ENUMS = {
        'role': {'admin','editor','viewer','guest','user'},
        'status': {'active','banned','pending'},
        'method': {'GET','POST','PUT','PATCH','DELETE'},
        'order_status': {'pending','paid','shipped','completed','cancelled'},
    }
    def validate_enum(field, value):
        allowed = ENUMS.get(field, set())
        if not allowed: return True, ''
        ok = value in allowed
        return ok, f"'{value}' not in {sorted(allowed)}" if not ok else ''
    cases = [
        ('role','admin'),('role','superuser'),('status','active'),
        ('status','deleted'),('method','GET'),('method','CONNECT'),
        ('order_status','paid'),('order_status','processing'),
    ]
    for field, val in cases:
        ok, msg = validate_enum(field, val)
        print(f"{field}={val!r}: ok={ok}" + (f" => {msg}" if msg else ''))

示例

输入
solve()
期望输出
role='admin': ok=True
role='superuser': ok=False => 'superuser' not in ['admin', 'editor', 'guest', 'user', 'viewer']
status='active': ok=True
status='deleted': ok=False => 'deleted' not in ['active', 'banned', 'pending']
method='GET': ok=True
method='CONNECT': ok=False => 'CONNECT' not in ['DELETE', 'GET', 'PATCH', 'POST', 'PUT']
order_status='paid': ok=True
order_status='processing': ok=False => 'processing' not in ['cancelled', 'completed', 'paid', 'pending', 'shipped']
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码