python-计算每个数字的出现次数
问题内容:
我有一长串数字,用逗号分隔。我可以搜索并计算大多数数字或更准确地说是2位数数字的出现次数。
如果我有一个数字序列,例如: 1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2
并且我想计算该数字1
出现多少次,我应该真正得到5
。
但是,因为它在计算1
中10
,11
和12
,我得到9
。
有谁知道如何使以下代码仅匹配整个“字符串”?
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
:
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),因为它会为每个唯一数字迭代一次数字列表。