如何将以下列表列表转换为Python

时间:2015-04-24 02:28:44

标签: python python-2.7 dictionary data-structures

我有以下列表清单。

[["172.27.219.11", "First_Host", 13L, Decimal("44.8276")]
 ["172.27.219.11", "Second_Host", 16L, Decimal("55.1724")]
 ["172.27.241.210", "Second_Host", 19L, Decimal("100.0000")]
 ["52.11.201.64", "First_Host", 30L, Decimal("3.9164")]
 ["52.11.201.64", "Second_Host", 736L, Decimal("96.0836")]]

我必须通过ip_addresses对它们进行分组。因此,例如对于第一个ip_address 172.27.219.11,我必须将First_HostSecond_Host及其各自的十进制值分组为流量。如果没有重复IP地址,那么只需添加即可。所以基本上在完成上面的例子后我应该把它作为。

[
    {
        "ip" : "172.27.219.11",
        "value": [
                    {
                        "name" : "First_Host",
                        "traffic" : 44.8276,
                    },
                    {
                        "name": "Second_Host",
                        "traffic": 55.1724,
                    }
                ]
        "ip" : "172.27.241.210"
        "value": [
                    {
                        "name": "Second_Host",
                        "traffic": 100 ,
                    }

               ]
        "ip": "52.11.201.64"
        "value": [
                    {
                        "name": "Second_Host",
                        "traffic": 3.9164,
                    },
                    {
                        "name": "First_Host",
                        "traffic": 96.0836,
                    }

               ]

    }
]

我需要帮助以上述格式制定回复。

1 个答案:

答案 0 :(得分:1)

raw_data = [["172.27.219.11", "First_Host", 13L, Decimal("44.8276")],
 ["172.27.219.11", "Second_Host", 16L, Decimal("55.1724")],
 ["172.27.241.210", "Second_Host", 19L, Decimal("100.0000")],
 ["52.11.201.64", "First_Host", 30L, Decimal("3.9164")],
 ["52.11.201.64", "Second_Host", 736L, Decimal("96.0836")]]



final = [{'ip':j} for j in list(set([i[0] for i in raw_data]))]

for i in raw_data:
    for j in final:
        if i[0]== j['ip']:
            if j.has_key('value'):
                j['value'].append({'name':i[1],'traffic':float(i[3])})
            else:
                j['value'] = []
                j['value'].append({'name':i[1],'traffic':float(i[3])})