python怎么分组统计_python写的简单分组统计脚本

访问日志内容:

'asdfasd'|2222|'asdfasdf'|{'phone':'13511020335','name':'lsq','address':'asdfasdfasdfasf'}

'asdfasd'|2222|'asdfasdf'|{'phone':'13511020335','name':'lsq','address':'asdfasdfasdfasf'}

'asdfasd'|2222|'asdfasdf'|{'phone':'13810210010','name':'llj','address':'asdfasdfasdfasf'}

'asdfasd'|2222|'asdfasdf'|{'phone':'18900102987','name':'ljk','address':'asdfasdfasdfasf'}

'asdfasd'|2222|'asdfasdf'|{'phone':'13810210010','name':'llj','address':'asdfasdfasdfasf'}

'asdfasd'|2222|'asdfasdf'|{'phone':'13511020335','name':'lsq','address':'asdfasdfasdfasf'}

'asdfasd'|2222|'asdfasdf'|{'phone':'13511020335','name':'lsq','address':'asdfasdfasdfasf'}

'asdfasd'|2222|'asdfasdf'|{'phone':'13511020335','name':'lsq','address':'asdfasdfasdfasf'}

'asdfasd'|2222|'asdfasdf'|{'phone':'18900102987','name':'ljk','address':'asdfasdfasdfasf'}

统计需求:按电话和用户名来统计访问次数

可以用三种方法:

### 1. collections  Counter

from collections import Counter

l = []

for s in open('a.txt'):

d = eval(s.split('|')[-1].strip())

l.append(d['phone']+ '||' + d['name'])

Counter(l)

Counter({'13511020335||lsq': 5, '18900102987||ljk': 2, '13810210010||llj': 2})

### 2.list.count

l = []

for s in open('a.txt'):

d = eval(s.split('|')[-1].strip())

l.append(d['phone']+ '||' + d['name'])

a = {}

for i in l:

if l.count(i)>=1:

a[i] = l.count(i)

print a

>>> print a

{'18900102987||ljk': 2, '13810210010||llj': 2, '13511020335||lsq': 5}

### 3.dict in

dr = {}

for s in open('a.txt'):

d = eval(s.split('|')[-1].strip())

k_dr = d['phone']+ "||" + d['name']

if k_dr in dr:

dr[k_dr] = dr[k_dr] + 1

else:

dr[k_dr] = 1

>>> print dr

{'18900102987||ljk': 2, '13810210010||llj': 2, '13511020335||lsq': 5}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值