python - 如何从列表中优先提取多个匹配值之一?

标签 python

我有一个字典列表

list_ = [
    {'id': '1', 'name': 'ABC', 'email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5f5c5d7e59535f5752105d5153" rel="noreferrer noopener nofollow">[email protected]</a>', 'role': 'Tester'},
    {'id': '2', 'name': 'CDE', 'email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c6f68694c6b616d6560226f6361" rel="noreferrer noopener nofollow">[email protected]</a>', 'role': 'Developer'},
    {'id': '3', 'name': 'fgh', 'email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdabaaa58daaa0aca4a1e3aea2a0" rel="noreferrer noopener nofollow">[email protected]</a>', 'role': 'Developer'},
    {'id': '2', 'name': 'CDE', 'email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a595e5f7a5d575b535614595557" rel="noreferrer noopener nofollow">[email protected]</a>', 'role': 'Tester'},
    {'id': '1', 'name': 'ABC', 'email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9d9e9fbc9b919d9590d29f9391" rel="noreferrer noopener nofollow">[email protected]</a>', 'role': 'Developer'}
]

我正在尝试从与 key 匹配的列表中提取特定的角色

开发人员 的优先级高于测试人员。如果对于特定 ID,同时存在 DeveloperTester,则输出应为 Developer

但是,如果列表中首先出现的是 Tester,那么我的代码将无法工作,它将给出 Tester 而不是 Developer

我怎样才能正确地做到这一点?我需要添加 break 语句吗?

def find_role(id_, list_):
    role = 'user'
    for each in list_:
        if id_ == each['id'] and each['role'] == 'Developer':
            role = 'Developer'
            return role
        if id_ == each['id'] and each['role'] == 'Tester':
            role = 'Tester'
            return role
    return role
find_role('1', list_)

最佳答案

您当前的脚本不评估角色优先级。相反,它会返回您选择的角色集中的第一个角色。

def find_role(id_, list_):
    role = 'user'
    for each in list_:
        if id_ == each['id']:
            # check for first role priority
            if each['role'] == 'Developer':
                role = 'Developer'
            # if first role priority has not been assigned, check for next
            elif role != 'Developer' and each['role'] == 'Tester':
                role = 'Tester'
    return role
find_role('1', list_)

关于python - 如何从列表中优先提取多个匹配值之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68286732/

相关文章:

python - Django:每次更新都会调用模型 __init__()

python - Pandas 数据框到字典的稀疏字典

python - 在 Python 中指定 input() 类型?

python - 写出类中的完整输入列表以进行模型预测

python - Python 是否有不连续的范围类?

python - 我如何捕获 SSL : CERTIFICATE_VERIFY_FAILED error python?

python - 是否可以将使用 Tkinter 创建的动画保存在文件中?

python - 求解仅给定几个变量的简单方程组

python - 放大 pygame 中的窗口导致滞后

python - 如何使用嵌套 np.where 语句有条件地将上述情况复制到数据帧的列中