我在python中有一个列表,例如:
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
我写了这个函数,但这可以用更简单的方式完成吗?
line = ['0', '1', '0', 'R', '1']
答案 0 :(得分:6)
你可以把它写成:
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'])
答案 1 :(得分:3)
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))
更短,更具可读性和可维护性。
答案 2 :(得分:3)
如果您的验证不太复杂,您可以自己编写一些验证助手:
#!/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。
尽管有名字,但它是一个Python数据验证库。它主要用于验证作为JSON,YAML等进入Python的数据。
答案 3 :(得分:0)
def checkcards():
return 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'] and len(line)==5
&#39;无&#39;是一个字符串,None是一个对象类型。确保你知道你想要使用哪一个。
答案 4 :(得分:0)
以下代码将有助于检查动态列表。
line = ['0', '1', '0', 'R', '1']
check_list = [
['0', '1'],
['0', '1', 'None'],
['0', '1', 'None'],
['R', 'L'],
['0', '1']
]
def check():
for l, item in enumerate(line):
if not item in check_list[l]:
return False
elif l == 4:
### comes here only if each item in line is found in the check_list
return True