python - 计算字典中 SPECIFIC/CERTAIN 值的数量
问题描述
我不想计算字典中的值的数量
这是我的代码:
def use_favcolors(fav_color):
count = 0
for green in fav_color:
if green == fav_color:
count += 1
print count
def main():
use_favcolors({"John": "green", "Bobby": "blue", "PapaSanta": "yellow"})
main()
为什么会打印 0?既然字典里有绿色,不应该打印1吗?
解决方案
您需要迭代字典的值。目前,您迭代字典中的键,而无需访问值。
请注意,这for i in fav_color
是在 Python 中迭代键的惯用方式。
Pythonic 迭代值的方法是使用dict.values
:
def use_favcolors(fav_color):
count = 0
for color in fav_color.values():
if color == 'green':
count += 1
print count
实现逻辑的另一种方法是使用sum
生成器表达式。这是有效True == 1
的,因为 Boolean 是int
.
d = {"John": "green", "Bobby": "blue", "PapaSanta": "yellow"}
res = sum(i=='green' for i in d.values()) # 1
推荐阅读
- javascript - 如何使我的 HTTP 请求的行为与表单相同
- reactjs - 为什么删除后必须手动刷新页面?
- sql - 如何从我的 postgresql 函数中消除重复项?
- ansible - 如何将角色和模板整合到同一个剧本中
- reactjs - 有没有办法在打字稿中描述反应生命周期方法?
- swift - NSTableView 中的子类 NumberFormatter 未格式化
- c# - MVC 单字符串 JSON 帖子总是在控制器中为空
- node.js - 在 Node.js 中使用 Cloud Function 获取条带凭据的 POST 请求
- javascript - 即使在 array.Array 中推入元素之后,循环外也显示为空
- excel - 从计算机检索用户名