2

我有一个看起来像这样的列表列表

[['ip1',404],
['ip1',200],
['ip1',200],
['ip2',200],
['ip2',200],
['ip2',504]]

我需要制作一个按 ip 地址计算状态码的字典。

results = {'ip1':{404:1,200:2},'ip2':{200:2,504:1}}
4

5 回答 5

9

集合中的工具可以解决这个问题:

>>> from collections import defaultdict, Counter
>>> d = defaultdict(Counter)
>>> for ip, code in [['ip1',404], ['ip1',200], ['ip1',200],
                     ['ip2',200], ['ip2',200], ['ip2',504]]:
        d[ip][code] += 1

>>> dict(d)
{'ip2': Counter({200: 2, 504: 1}), 'ip1': Counter({200: 2, 404: 1})}
于 2012-06-17T07:39:25.610 回答
3
>>> from collections import defaultdict
>>> d = defaultdict(lambda: defaultdict(int))
>>> ips = [['ip1',404],['ip1',200],['ip1',200],['ip2',200],['ip2',200],['ip2',504]]
>>> for ip,num in ips:
        d[ip][num] += 1

>>> d
defaultdict(<function <lambda> at 0x00000000035D6648>, {'ip2': defaultdict(<class 'int'>, {200: 2, 504: 1}), 'ip1': defaultdict(<class 'int'>, {200: 2, 404: 1})})
于 2012-06-17T07:33:56.890 回答
2

试试这个:

values =   [['ip1',404],
            ['ip1',200],
            ['ip1',200],
            ['ip2',200],
            ['ip2',200],
            ['ip2',504]]

counts = {}

for value in values:
    ip, status_code = value
    if ip not in counts:
        counts[ip] = {}
    if status_code not in counts[ip]:
        counts[ip][status_code] = 0
    counts[ip][status_code] += 1

{'ip2': {200: 2, 504: 1}, 'ip1': {200: 2, 404: 1}}

它应该适用于几乎任何 python 版本。

于 2012-06-17T07:33:58.827 回答
0
>>> l
[['ip1', 404],
 ['ip1', 200],
 ['ip1', 200],
 ['ip2', 200],
 ['ip2', 200],
 ['ip2', 504]]

>>> {ip: {code: l.count([ip, code])
...    for code in (p[1] for p in l if p[0]==ip)}
...          for ip in (p[0] for p in l)}
{'ip1': {200: 2, 404: 1}, 'ip2': {200: 2, 504: 1}}
于 2012-06-17T07:33:16.717 回答
0
L = [[ip1,404], [ip1,200], [ip1,200], [ip2,200], [ip2,200], [ip2,504]]
D = {}

for entry in L:
    ip = entry[0]
    code = entry[1]
    ip_entry = D.get(ip, {})
    ip_entry[code] = ip_entry.get(code, 0) + 1
    D[ip] = ip_entry
于 2012-06-17T07:43:13.677 回答