python-3.x - 如果满足条件,如何比较字典中的两个值并返回第三个值?
问题描述
我在寻找解决这个问题的方法时遇到了一些麻烦。我需要比较属于字典中不同键的项目。如果比较等于我的参数,我需要将第三个(新)元素插入到同一个字典的新键中。下面是我打算做的一个例子。希望它更容易理解:
A={"names":["jason","peter","mary"],"ages":[25,35,45],"health":["Good","Good","Poor"]}
我需要分别将 的每个值"ages"
与 的每个项目进行比较"health"
。如果 in 的值"ages"
>20 并且 in 的值"health"
是"Good"
,我需要根据之前进行的比较结果,将值"yes"
或添加"no"
到该字典中的新键。"fit"
我一直在寻找所有可能的方法来做到这一点,但没有成功。
解决方案
您的数据组织不善;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'])]
推荐阅读
- css - 在 angular.json 和 index.html 导入之间设置 Angular 应用程序的引导版本顺序
- flutter - 如何使用 Flutter 在列表中显示多个 GoogleMap
- vb.net - 粘贴到 RichTextBox 或其他解决方案时调整图像大小?
- python - Pandas Numpy np.where 处理空值
- javascript - 打字稿导入返回“找不到模块”
- node.js - 节点http没有incomingMessage
- javascript - 使用 jQuery 或 JavaScript 检查复选框值
- angular - Keycloak-angular 获取其他客户端的令牌
- reactjs - Echart 配置不允许我在图例符号中居中图例文本
- scala - 如果下游仍在工作,如何在 Akka Streams 中为下游删除消息