热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在python中执行此聚合-Howtocarryoutthisaggregationinpython

Ihavethefollowinglistofdictionarieswhichcontainsthecountryandthevaluesforcorrespondin

I have the following list of dictionaries which contains the country and the values for corresponding servers.

我有以下字典列表,其中包含国家和相应服务器的值。

[
    {'country': 'KR', 'values': ['Server1']},
    {'country': 'IE', 'values': ['Server1', 'Server3', 'Server2']},
    {'country': 'IE', 'values': ['Server1', 'Server3']},
    {'country': 'DE', 'values': ['Server1']},
    {'country': 'DE', 'values': ['Server2']},
]

Now I need to calculate the percentage of each server for a particular country. So for instance, for IE the sum total of both the lists is 5 . Hence the percentage will be calculated as (2/5)*100 for Server1 as there are two Server1 out of five for IE and similarly for the rest and then add the percentage for Server1 in the dict with percent as key. So essentially for the above structure the output becomes.

现在我需要计算特定国家/地区的每台服务器的百分比。因此,例如,对于IE,两个列表的总和为5。因此,对于Server1,百分比将被计算为(2/5)* 100,因为IE中有两个Server1,其余的类似于其余,然后在dict中添加Server1的百分比,其中百分比为关键。因此,基本上对于上述结构,输出变为。

[
    {"country": "KR", "percent": "100.0000", "values": ["Server1-100.0000"]},
    {"country": "IE", "percent": "40.000", "values": ["Server1-40.0", "Server3-40.0", "Server2-20.0"]},
    {"country" : "DE", "percent" : "50.0", "values" : ["Server1-50.0", "Server2-50.0"]},
]

I tried the following code.

我尝试了以下代码。

for i in range(len(response) - 1):
   for j in range((i+1), len(response) - 1):
     if response[i]['country'] == response[j]['country']:
       print response[i]['country'], response[j]['country']
       total = len(response[i]['values']) +  len(response[j]['values'])
       print total
       for item in response[i]['values']:
         for ktem in response[j]['values']:
           if item == ktem:
              if item == 'Server1':
                response[i]['percent'] =  200/total
              else:
                response[i][percent] = 0
              del response[j]

I am stuck to proceed further to get the percentage part correct. Any help?

我坚持继续进一步让百分比部分正确。有帮助吗?

2 个解决方案

#1


I have a more compact method.

我有一个更紧凑的方法。

I think it's more readable and easy to understand. You can refer as below:

我认为它更易读,更容易理解。你可以参考如下:

This is your var I delcare response:

这是你的var I delcare回复:

respOnse= [
    {'country': 'KR', 'values': ['Server1']},
    {'country': 'IE', 'values': ['Server1', 'Server3', 'Server2']},
    {'country': 'IE', 'values': ['Server1', 'Server3']},
    {'country': 'DE', 'values': ['Server1']},
    {'country': 'DE', 'values': ['Server2']},
]

Let's merge the values.

让我们合并这些值。

new_res = {}
for e in response:
    if e['country'] not in new_res:
        new_res[e['country']] = e['values']
    else:
        new_res[e['country']].extend(e['values'])

You can print new_res if you want to know its content. It's like as below:

如果您想了解其内容,可以打印new_res。它如下所示:

{
    'KR': ['Server1'],
    'DE': ['Server1', 'Server2'],
    'IE': ['Server1', 'Server3', 'Server2', 'Server1', 'Server3']
}

Invoking collections module collects elements:

调用集合模块收集元素:

from collections import Counter
new_list = []
for country, values in new_res.items():
    # elements are stored as dictionary keys and their counts are stored as dictionary values
    merge_values = Counter(values)

    # calculate percentage
    new_values = []
    total = sum(merge_values.values())    
    for server_name, num in merge_values.items():
        #ex: Server1-40.0
        new_values.append("{0}-{1:.1f}".format(server_name, num*100/total))

    percent = merge_values["Server1"]*1.0*100/total

    new_list.append({"country": country,
                     "percent": percent,
                     "values": new_values})

You can print new_list when finishing calculating result:

完成计算结果后可以打印new_list:

[{'country': 'KR', 'percent': 100.0, 'values': ['Server1-100.0']},
 {'country': 'DE', 'percent': 50.0,  'values': ['Server1-50.0', 'Server2-50.0']},
 {'country': 'IE', 'percent': 40.0,  'values': ['Server1-40.0', 'Server2-20.0', 'Server3-40.0']}]

So you can get answer you want.

所以你可以得到你想要的答案。

#2


Let's say you have

让我们说你有

orig = [
    {'country': 'KR', 'values': ['Server1']},
    {'country': 'IE', 'values': ['Server1', 'Server3', 'Server2']},
    {'country': 'IE', 'values': ['Server1', 'Server3']},
    {'country': 'DE', 'values': ['Server1']},
    {'country': 'DE', 'values': ['Server2']},
]

You can create a new dictionary that has a list of what servers are in what countries and their counts

您可以创建一个新字典,其中列出了哪些服务器位于哪些国家/地区及其计数

newDict = {}
for c in orig:
    if c['country'] not in newDict:
        newDict[c['country']] = dict()
    for s in c['values']:
        if s in newDict[c['country']]:
            newDict[c['country']][s] = newDict[c['country']][s] + 1
        else:
            newDict[c['country']][s] = 1

which will be of the form:

其形式如下:

{'KR': {'Server1': 1}, 
 'DE': {'Server1': 1, 'Server2': 1}, 
 'IE': {'Server1': 2, 'Server2': 1, 'Server3': 2}}

You can then calculate the percentages as such:

然后,您可以计算百分比:

output = []
for country in newList:
    total = 0
    for server in newList[country]:
        total = total + newList[country][server]    
    output.append({"country": country, "percent": (100.0 * newList[country]['Server1'])/total})

which will produce

这将产生

[{'country': 'KR', 'percent': 100.0}, 
 {'country': 'DE', 'percent': 50.0}, 
 {'country': 'IE', 'percent': 40.0}]

I'll leave it as an exercise for the reader to optimize and add the other fields that you want

我将把它作为练习让读者优化并添加你想要的其他字段


推荐阅读
  • http:my.oschina.netleejun2005blog136820刚看到群里又有同学在说HTTP协议下的Get请求参数长度是有大小限制的,最大不能超过XX ... [详细]
  • Python瓦片图下载、合并、绘图、标记的代码示例
    本文提供了Python瓦片图下载、合并、绘图、标记的代码示例,包括下载代码、多线程下载、图像处理等功能。通过参考geoserver,使用PIL、cv2、numpy、gdal、osr等库实现了瓦片图的下载、合并、绘图和标记功能。代码示例详细介绍了各个功能的实现方法,供读者参考使用。 ... [详细]
  • 本文介绍了使用cacti监控mssql 2005运行资源情况的操作步骤,包括安装必要的工具和驱动,测试mssql的连接,配置监控脚本等。通过php连接mssql来获取SQL 2005性能计算器的值,实现对mssql的监控。详细的操作步骤和代码请参考附件。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • 图解redis的持久化存储机制RDB和AOF的原理和优缺点
    本文通过图解的方式介绍了redis的持久化存储机制RDB和AOF的原理和优缺点。RDB是将redis内存中的数据保存为快照文件,恢复速度较快但不支持拉链式快照。AOF是将操作日志保存到磁盘,实时存储数据但恢复速度较慢。文章详细分析了两种机制的优缺点,帮助读者更好地理解redis的持久化存储策略。 ... [详细]
  • 计算机存储系统的层次结构及其优势
    本文介绍了计算机存储系统的层次结构,包括高速缓存、主存储器和辅助存储器三个层次。通过分层存储数据可以提高程序的执行效率。计算机存储系统的层次结构将各种不同存储容量、存取速度和价格的存储器有机组合成整体,形成可寻址存储空间比主存储器空间大得多的存储整体。由于辅助存储器容量大、价格低,使得整体存储系统的平均价格降低。同时,高速缓存的存取速度可以和CPU的工作速度相匹配,进一步提高程序执行效率。 ... [详细]
  • 本文介绍了Web学习历程记录中关于Tomcat的基本概念和配置。首先解释了Web静态Web资源和动态Web资源的概念,以及C/S架构和B/S架构的区别。然后介绍了常见的Web服务器,包括Weblogic、WebSphere和Tomcat。接着详细讲解了Tomcat的虚拟主机、web应用和虚拟路径映射的概念和配置过程。最后简要介绍了http协议的作用。本文内容详实,适合初学者了解Tomcat的基础知识。 ... [详细]
  • 本文介绍了计算机网络的定义和通信流程,包括客户端编译文件、二进制转换、三层路由设备等。同时,还介绍了计算机网络中常用的关键词,如MAC地址和IP地址。 ... [详细]
  • 本文介绍了在使用Python中的aiohttp模块模拟服务器时出现的连接失败问题,并提供了相应的解决方法。文章中详细说明了出错的代码以及相关的软件版本和环境信息,同时也提到了相关的警告信息和函数的替代方案。通过阅读本文,读者可以了解到如何解决Python连接服务器失败的问题,并对aiohttp模块有更深入的了解。 ... [详细]
  • 本文讨论了如何使用IF函数从基于有限输入列表的有限输出列表中获取输出,并提出了是否有更快/更有效的执行代码的方法。作者希望了解是否有办法缩短代码,并从自我开发的角度来看是否有更好的方法。提供的代码可以按原样工作,但作者想知道是否有更好的方法来执行这样的任务。 ... [详细]
  • 本文介绍了Python爬虫技术基础篇面向对象高级编程(中)中的多重继承概念。通过继承,子类可以扩展父类的功能。文章以动物类层次的设计为例,讨论了按照不同分类方式设计类层次的复杂性和多重继承的优势。最后给出了哺乳动物和鸟类的设计示例,以及能跑、能飞、宠物类和非宠物类的增加对类数量的影响。 ... [详细]
  • 本文详细介绍了如何使用MySQL来显示SQL语句的执行时间,并通过MySQL Query Profiler获取CPU和内存使用量以及系统锁和表锁的时间。同时介绍了效能分析的三种方法:瓶颈分析、工作负载分析和基于比率的分析。 ... [详细]
  • 本文介绍了在Python张量流中使用make_merged_spec()方法合并设备规格对象的方法和语法,以及参数和返回值的说明,并提供了一个示例代码。 ... [详细]
  • 本文介绍了200个经典c语言源代码,包括函数的使用,如sqrt函数、clanguagefunct等。这些源代码可以帮助读者更好地理解c语言的编程方法,并提供了实际应用的示例。 ... [详细]
  • Java编程实现邻接矩阵表示稠密图的方法及实现类介绍
    本文介绍了Java编程如何实现邻接矩阵表示稠密图的方法,通过一个名为AMWGraph.java的类来构造邻接矩阵表示的图,并提供了插入结点、插入边、获取邻接结点等功能。通过使用二维数组来表示结点之间的关系,并通过元素的值来表示权值的大小,实现了稠密图的表示和操作。对于对稠密图的表示和操作感兴趣的读者可以参考本文。 ... [详细]
author-avatar
VASTEw
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有