有没有更简短的方法来写这个方法?

2024-09-19 23:28:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个列表,应该如下所示,例如:

line = ['0', '1', '0', 'R', '1']

我写了这个函数,但是可以用更简单的方法吗?你知道吗

def checkCardCommands(line):
    if line[0] == '0' or line[0] == '1':
        if line[1] == '0' or line[1] == '1' or line[1] == 'None':
            if line[2] == '0' or line[2] == '1' or line[2] == 'None':
                if line[3] == 'R' or line[3] == 'L':
                    if line[4] == '0' or line[4] == '1':
                        if len(line) == 5:
                            return True
                        else:
                            return False
                    else:
                        return False
                else:
                    return False
            else:
                return False
        else:
            return False
    else:
        return False

Tags: or方法函数nonefalsetrue列表len
3条回答

你可以这样写:

def checkCardCommands(line):
    return (len(line) == 5
      and line[0] in ['0', '1']
      and line[1] in ['0', '1', 'None']
      and line[2] in ['0', '1', 'None']
      and line[3] in ['R', 'L']
      and line[4] in ['0', '1'])
def check(line):
    spec = [
        ['0', '1'],
        ['0', '1', 'None'],
        ['0', '1', 'None'],
        ['R', 'L'],
        ['0', '1']
    ]

    return len(line) == len(spec) and all(ln in spc for ln, spc in zip(line, spec))

更简短,更易于阅读和维护。你知道吗

如果您的验证不太复杂,您可以自己编写一些验证帮助程序:

#!/usr/bin/env python3
# coding: utf-8

def validate(schema, seq):
    """
    Validates a given iterable against a schema. Schema is a list
    of callables, taking a single argument returning `True` if the
    passed value is valid, `False` otherwise.
    """
    if not len(schema) == len(seq):
        raise ValueError('length mismatch')
    for f, item in zip(schema, seq):
        if not f(item):
            raise ValueError('validation failed: %s' % (item))
    return True

if __name__ == '__main__':

    # two validation helper, add more here
    isbool = lambda s: s == '0' or s == '1'
    islr = lambda s: s == 'L' or s == 'R'

    # define a schema
    schema = [isbool, isbool, isbool, islr, isbool]
    # example input
    line = ['0', '1', '0', 'R', '1']

    # this is valid
    validate(schema, ['0', '1', '0', 'R', '1'])

    # ValueError: validation failed: X
    validate(schema, ['0', '1', '0', 'R', 'X'])

    # ValueError: length mismatch
    validate(schema, ['0', '1'])

有关更高级的数据结构模式验证,请参阅voluptuous。你知道吗

Voluptuous, despite the name, is a Python data validation library. It is primarily intended for validating data coming into Python as JSON, YAML, etc.

相关问题 更多 >