python - 如何为列表中的每个值获取一个数字?
问题描述
Python 和一般编程的新手。我正在尝试创建一个程序,该程序将从 Cisco UCM 中提取设备计数。目前,我可以让程序打印出来自 CUCM 的模型列表,但最终我想看看每个模型出现了多少。例如,如果 CUCM 服务器有 5 个 8845 和 3 个 8865,我希望 Python 能够快速显示该信息。
这是我当前的代码:
if __name__ == '__main__':
resp = service.listPhone(searchCriteria={'name':'SEP%'}, returnedTags={'model': ''})
model_list = resp['return'].phone
for phone in model_list:
print(phone.model)
我试图从 Pandas 创建一个 DataFrame,但无法让它工作。我认为问题在于我没有将 phone.model 部分存储为变量,但无法弄清楚如何做到这一点。
我的目标是最终获得如下内容的输出:
8845 - 5
8865 - 3
在此先感谢您的帮助!
解决方案
看起来你在这里不需要 Pandas,普通的旧 Python 可以编写counts
如下所示的帮助器 -</p>
from collections import defaultdict
def counts(xs):
counts = defaultdict(int)
for x in xs:
counts[x] += 1
return counts.items()
然后你可以像这样使用它——</p>
models = ['a', 'b', 'c', 'c', 'c', 'b']
for item, count in counts(models):
print(item, '-', count)
输出将是——</p>
a - 1
b - 2
c - 3
推荐阅读
- django - django - AbstractUser 属性消失了....?
- .net - 如何使 Nest Elasticsearch 不区分大小写
- laravel - 显示数据视图时处理空表
- javascript - Fabric.js 替换图像对象中的颜色
- json - 如何在 TypeScript 中使用 JSON 对象的值?
- php - 如何将 3 个表相互关联
- javascript - 如何在Javascript中制作like按钮?
- oauth-2.0 - 有没有办法更改 Postman OAuth 2 客户端凭据请求的内容类型?
- c# - 从 ASP.NET Core 应用程序访问 Azure KeyVault 中的证书
- java - 需要帮助才能使 YouTube Java API 代码正常工作