python-计算每个数字的出现次数 [英] python - Count number of occurrences of each number
问题描述
我有一长串数字,用逗号分隔.我可以搜索并计算大多数数字(或更准确地说是2位数字)的出现次数.
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.
如果我有一个数字序列,例如:
1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2
而我想计算数字1
出现多少次,我真的应该得到5
.
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
.
但是,因为它正在计算10
,11
和12
中的1
,所以我得到了9
.
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)
推荐答案
在2.7+上,只需split
并使用collections.Counter
:
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(','))
或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
如果要使用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))
但是它是O(m * n)而不是O(n),因为它会为每个唯一数字迭代一次数字列表.
but it's O(m*n) rather than O(n) because it iterates the list of numbers once for each unique number.
这篇关于python-计算每个数字的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!