我有一长串数字,用逗号分隔。我可以搜索和计算大多数数字的出现次数,或者更准确地说,2 位数字。
如果我有一个数字序列,例如:
1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2
我想计算数字 1
出现了多少次我真的应该得到 5
。
但是,因为它正在计算 10
、11
和 12
中的 1
,所以我得到了 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+ 上,只需拆分
并使用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),因为它为每个唯一数字迭代一次数字列表。
关于python - 计算每个数字的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7439578/