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

try this:

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}}

it should work on virtually any python version.

于 2012-06-17T07:33:58.827 に答える
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 に答える
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 に答える