统计个数

in 文件每行有三列,tab分隔,统计最后一列每个字符出现的字数,其实是数字,但是当作字符处理。没什么问题,主要是最后想要对dict 按key值排序出了问题,python3 的dict不能用sort 什么的,最后也只能搞成按字符排序,而不是按key的数值排序。

摘抄一段python 文档

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
使用collections 里的 OrderedDict() ,写的时候试了下,把key值转换成int 来compare,ok,好丑

import collections
file=open('filename.txt','r')
count={}
f1=open('c3.txt','w')
for lines in file.readlines():
	lines=lines.rstrip('\n')
	line=lines.split('\t')[2]
	if line in count:
		count[line]+=1
	else:
		count[line]=1
f=open('out.txt','w')
count=collections.OrderedDict(sorted(count.items(), key=lambda t: int(t[0])))
for i in count:
	i=str(i)
	count[i]=str(count[i])
	f.write(i+'\t'+count[i]+'\n')
f.close


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值