社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  David Zemens  »  全部回复
回复总数  1
6 年前
回复了 David Zemens 创建的主题 » python使用if语句验证多个值

如果您不需要一个object/return中的所有输出,我们可以对第一个函数进行一些调整。

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']}]})