如何为列表中的每个值获取一个数字?

2024-04-29 17:04:18 发布

您现在位置:Python中文网/ 问答频道 /正文

对Python和一般编程都是新手。我试图创建一个程序,将从思科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中创建一个数据帧,但无法使其工作。我想问题是我没有储存电话.型号部分作为一个变量,但我不知道如何做到这一点。你知道吗

我的目标是最终得到如下输出:

8845 - 5
8865 - 3

提前感谢您的帮助!你知道吗


Tags: name模型程序服务器列表model编程phone
2条回答

在使用CUCM输出后,我这样做:

modellist={}
for phone in resp['return']["phone"]:
    if phone["model"] in modellist.keys():
        modellist[phone["model"]] += 1
    else:
        modellist[phone["model"]] = 1


for phone, count in modellist.items():
    print(phone, " - " ,count)

看起来这里不需要熊猫,普通的老Python可以在下面编写counts这样的助手-

from collections import defaultdict


def counts(xs):
    counts = defaultdict(int)
    for x in xs:
        counts[x] += 1
    return counts.items()

然后你可以像这样使用它-

models = ['a', 'b', 'c', 'c', 'c', 'b']

for item, count in counts(models):
    print(item, '-', count)

输出将为-

a - 1
b - 2
c - 3

相关问题 更多 >