Example1要检查单个值:
def validate(self, data, check, col):
output = []
for key, value in data.iteritems():
try:
if value[col] == check:
output.append("{},{},Passed".format(key,value[col]))
else:
output.append("{},{},Failed".format(key,value[col]))
except IndexError as e:
pass
return output
data1 = {key1:['a','b','c','ok'], key2:['a','b','c','down']}
check = "ok"
col = 3
print self.validate(data1, check, col)
输出:
['key1','ok','Passed', 'key2','down','Failed']
Example2要检查两个值:
data1 = {key1:['a','b','c','ok', "True"], key2:['a','b','c','down', "False"]}
def validate(self, data, check1, check2, col1, col2):
output = []
for key, value in data.iteritems():
try:
if value[col1] == check1 and value[col2] == check2:
output.append("{},{},{},Passed".format(key,value[col1], value[col2]))
else:
output.append("{},{},Failed".format(key,value[col1], value[col2]))
except IndexError as e:
pass
return output
有一种方法可以在一个代码中实现上述两个示例(验证多个值一,二,三,四)
答案 0 :(得分:1)
为什么不将all
与列/校验值的压缩列表一起使用?
if all(value[col] == check for col,check in zip((col1,col2),(check1,check2))):
如果您有更多参数,建议您打开:
def validate(self, data, check1, check2, col1, col2):
进入
def validate(self, data, check_values, columns):
因此您可以适应:
if all(value[col] == check for col,check in zip(columns,check_values)):
此外,由于这些值和列已链接,因此可以直接传递元组列表或将它们链接在一起的字典到validate
。
答案 1 :(得分:0)
如果您不需要在一个对象/返回中全部输出,我们可以对您的第一个功能进行一些调整。
from collections import defaultdict
def validate(data, check_value, column_index):
# validating whether the list item at column_index == check_value
output = defaultdict(list)
for k,v in data.items(): # for python2, use data.iteritems()
if check_value in v and column_index <= len(v) and v[column_index] == check_value:
output[check_value].append({k: [v[column_index], 'passed']})
else:
output[check_value].append({k: [v[column_index], 'failed']})
return output
对于单值测试,这应该返回相同的预期结果。
您可以对多个值执行以下操作:
check_values = ['ok', 'b']
column_indices = [3, 2]
for value, index in zip(check_values, column_indices):
validate(data, value, index)
哪个返回:
defaultdict(<class 'list'>, {'ok': [{'key1': ['ok', 'passed']}, {'key2': ['down', 'failed']}]})
defaultdict(<class 'list'>, {'b': [{'key1': ['c', 'failed']}, {'key2': ['c', 'failed']}]})