python数字计算公式,python-计算每个数字的出现次数

I have a long string of numbers separated by commas. I can search and count the number of occurrences of most numbers, or more accurately, 2 digit numbers.

IF I have a number sequences like:

1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2

and I want to count how many times the number 1 appears I should really get 5.

However, because it is counting the 1 in 10,11 and 12, I am getting 9.

Does anyone know how to make the below code match ONLY whole "strings"?

def mostfreq(numString):

import json

maxNum=45

count=1

list={}

while count <= maxNum:

list[count] = 0

count+=1

#numString is the array with all the numbers in it

count=1

topTen = ""

while count <= maxNum:

list[count]=numString.count(str(count))

topTen = topTen+json.dumps(

{count: list[count]},

sort_keys=True,

indent=4)+","

count+=1

response_generator = ( "["+topTen[:-1]+"]" )

return HttpResponse(response_generator)

解决方案

On 2.7+, just split and use the collections.Counter:

from collections import Counter

numstring = "1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2"

numcount = Counter(numstring.split(','))

or, Pre-2.7:

from collections import defaultdict

numstring = "1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2"

numcount = defaultdict(int)

for num in numstring.split(','):

numcount[num] += 1

If you want to use count:

numstring = "1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2"

numlist = numstring.split(',')

numcount = dict((num, numlist.count(num)) for num in set(numlist))

but it's O(m*n) rather than O(n) because it iterates the list of numbers once for each unique number.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值