python 统计个数怎么统计
发布网友
发布时间:2022-04-25 07:46
我来回答
共2个回答
热心网友
时间:2022-04-07 13:06
# -*- coding: cp936 -*-
fruitfile=open(r"fruit.txt")
fruitdict={}
for line in fruitfile.readlines():
fruit=line.split()[1]
if fruitdict.has_key(fruit):
fruitdict[fruit]+=1
else:
fruitdict[fruit]=1
fruitlist=[]
for key,value in fruitdict.items():
fruitlist.append((key,value))
fruitlist.sort(lambda a,b:b[1],reverse=True)
if len(fruitlist)>=3:
print "出现次数前三的水果:"
print fruitlist[0][0],fruitlist[0][1]
print fruitlist[1][0],fruitlist[1][1]
print fruitlist[2][0],fruitlist[2][1]
print "\n\n所有水果出现次数:"
for key,value in fruitlist:
print key,value
其中fruit.txt为文件名
热心网友
时间:2022-04-07 14:24
# -*- coding: cp936 -*-
def f():
for line in open("data.txt"): #读取文件
yield line
def f2(f):
for line in f:
for i, k in enumerate(line.split()):
if i == 1:
yield k #得到水果
f = f()
d = f2(f)
l ={}
for i in d:
n=l.get(i)
if n is None:
l.update({i:1})
else:
l.update({i:n+1})
res=""
for i in range(3):
for j in l:
k= max(l)
res+= k +"->" +str(l[k]) +';'
l.pop(k)
break
print res #打印结果