首页 > 解决方案 > 如何为列表中的每个值获取一个数字?

问题描述

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

在此先感谢您的帮助!

标签: pythonpandaslistciscocucm

解决方案


看起来你在这里不需要 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

推荐阅读