gpt4 book ai didi

Python 使用 if 语句验证多个值

转载 作者:太空宇宙 更新时间:2023-11-04 04:25:41 25 4
gpt4 key购买 nike

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

有没有一种方法可以在一个代码中实现上述两个示例(验证多个值一、二、三、四)

最佳答案

为什么不将 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)):

而且,由于这些值和列是链接的,因此可以直接传递元组列表或将它们链接在一起的字典以验证

关于Python 使用 if 语句验证多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53558794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com