首页 > 解决方案 > 如果满足条件,如何比较字典中的两个值并返回第三个值?

问题描述

我在寻找解决这个问题的方法时遇到了一些麻烦。我需要比较属于字典中不同键的项目。如果比较等于我的参数,我需要将第三个(新)元素插入到同一个字典的新键中。下面是我打算做的一个例子。希望它更容易理解:

A={"names":["jason","peter","mary"],"ages":[25,35,45],"health":["Good","Good","Poor"]}

我需要分别将 的每个值"ages"与 的每个项目进行比较"health"。如果 in 的值"ages">20 并且 in 的值"health""Good",我需要根据之前进行的比较结果,将值"yes"或添加"no"到该字典中的新键。"fit"

我一直在寻找所有可能的方法来做到这一点,但没有成功。

标签: python-3.xdictionarycomparison

解决方案


您的数据组织不善;zip能够帮助。

定义一个辅助谓词:

def is_fit(age, health):
    if age > 20 and health == 'Good':
        return 'yes'
    else:
        return 'no'

重新组织数据:

import pprint

a = {'names': 'jason peter mary'.split(),
     'ages': [25, 35, 45],
     'health': ['Good', 'Good', 'Poor']}
pprint.pprint(list(zip(a['names'], a['ages'], a['health'])), width=30)

[('jason', 25, 'Good'),
 ('peter', 35, 'Good'),
 ('mary', 45, 'Poor')]

现在您可以一起访问每个人的属性:

for name, age, health in zip(a['names'], a['ages'], a['health']):
    if is_fit(age, health) == 'yes':
        print(name)
a['fit'] = [is_fit(age, health)
            for age, health
            in zip(a['ages'], a['health'])]

推荐阅读