我有一个看起来像这样的列表列表
[['ip1',404],
['ip1',200],
['ip1',200],
['ip2',200],
['ip2',200],
['ip2',504]]
我需要制作一个按 ip 地址计算状态码的字典。
results = {'ip1':{404:1,200:2},'ip2':{200:2,504:1}}
我有一个看起来像这样的列表列表
[['ip1',404],
['ip1',200],
['ip1',200],
['ip2',200],
['ip2',200],
['ip2',504]]
我需要制作一个按 ip 地址计算状态码的字典。
results = {'ip1':{404:1,200:2},'ip2':{200:2,504:1}}
集合中的工具可以解决这个问题:
>>> 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})}
>>> 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})})
试试这个:
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 版本。
>>> 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}}
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