python - 如何使用 Python 3 从列表中选择一个或多个项目
问题描述
我正在学习 Python 3 并试图回答以下问题,该问题要求在最后填写一行代码。我用粗体表示,但需要帮助来理解我做错了什么。我阅读了 StackOverflow 上发布的类似问题,但似乎都比我想要做的更高级。谢谢你。
请填写空白,以便以下代码成功遍历存储在“makeup_products”中的数据,并提取仅用于“Lips”的项目的阴影总数,并将总数存储在名为total_count_lip_shades
.
makeup_products = {"Products": [
{"Primer": {
"Shades": 15,
"Styles": 5,
"Location": "Face"
}
},
{"Lipstick": {
"Shades": 48,
"Styles": 3,
"Location": "Lips"
}
},
{"Lip liner": {
"Shades": 32,
"Styles": 4,
"Location": "Lips"
}
},
{"Blush": {
"Shades": 13,
"Styles": 2,
"Location": "Face"
}
},
{"Eye Liner": {
"Shades": 14,
"Styles": 7,
"Location": "Eye"
}
},
{"Travel Makeup Kit": {
"Shades": "N/A",
"Styles": 3,
"Location": "Face, Lips, Eye"
}
}
] }
total_count_lip_shades = 0
for item in makeup_products["Products"]:
for product in item:
**IF ITEM[PRODUCT]["LIP STICK", "LIP LINER"]**
shade_count = item[product]["Shades"]
total_count_lip_shades += shade_count
解决方案
您只需要一个if
检查Location
值是否等于的语句Lips
:
makeup_products = {"Products": [
{"Primer": {
"Shades": 15,
"Styles": 5,
"Location": "Face"
}
},
{"Lipstick": {
"Shades": 48,
"Styles": 3,
"Location": "Lips"
}
},
{"Lip liner": {
"Shades": 32,
"Styles": 4,
"Location": "Lips"
}
},
{"Blush": {
"Shades": 13,
"Styles": 2,
"Location": "Face"
}
},
{"Eye Liner": {
"Shades": 14,
"Styles": 7,
"Location": "Eye"
}
},
{"Travel Makeup Kit": {
"Shades": "N/A",
"Styles": 3,
"Location": "Face, Lips, Eye"
}
}
] }
total_count_lip_shades = 0
for item in makeup_products["Products"]:
for product in item:
if item[product]["Location"] == "Lips":
shade_count = item[product]["Shades"]
total_count_lip_shades += shade_count
推荐阅读
- oracle - Oracle 正则表达式,如果字符串以数字开头,则在开头查找长度为 3 的数字。否则,在末尾找到长度为 3 位的数字
- matlab - 如何在 MATLAB 中识别多个相交的多边形?
- .net-core - 如何在 .NET Core 中配置基于角色的身份验证?
- android - 获取从 ACTION_QS_TILE_PREFERENCES 长按的 Quick Tile
- python - Django Crispy 表单提交不适用于 TabHolder,但适用于字段集
- html - HTML 删除特定边框
- python - mousePressEvent 按下了哪个 QLabel
- html - 不能一次只让一个坍塌扩大
- python-3.x - 如何在 python 3.x 中打印字符串
- angular - Angular 4 - 获取 IIS 错误 404 页面,而不是根据用户权限重定向到我的 404 页面