我有一长串用逗号分隔的数字.我可以搜索和计算大多数数字的出现次数,或者更准确地说是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)
Run Code Online (Sandbox Code Playgroud)
在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(','))
Run Code Online (Sandbox Code Playgroud)
或者,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
Run Code Online (Sandbox Code Playgroud)
如果你想使用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))
Run Code Online (Sandbox Code Playgroud)
但它是O(m*n)而不是O(n),因为它为每个唯一的数字迭代一次数字列表.