【问题标题】:How do I get a number for each value in my list?如何为列表中的每个值获取一个数字?
【发布时间】:2019-11-14 18:01:55
【问题描述】:

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

提前感谢您的帮助!

【问题讨论】:

  • 嘿 Tandy,欢迎来到 SO,阅读 How to Ask,如果可能,请提供您的数据框的可重现样本,以便其他人可以看到您正在使用的数据类型。
  • @Tandy,谢谢你的问题,我了解了一些关于 CUCM SOAP 接口的知识(我只是一个网络人,不是 UC)......也许你已经有了这个链接,但是 AXL 架构在DevNet 似乎很有帮助:developer.cisco.com/docs/axl-schema-reference

标签: python pandas list cisco cucm


【解决方案1】:

这里看起来你不需要 Pandas,普通的旧 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

【讨论】:

    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2017-07-10
      • 2010-09-18
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      相关资源
      最近更新 更多