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

标签 python json

我有一长串数字,用逗号分隔。我可以搜索和计算大多数数字的出现次数,或者更准确地说,2 位数字。

如果我有一个数字序列,例如: 1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2 我想计算数字 1 出现了多少次我真的应该得到 5

但是,因为它正在计算 101112 中的 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/

相关文章:

Python:保存绘图而不是在 GUI 中打开它

python - 元类可以在类的范围内操作裸露的表达式吗?

python - 为什么FunctionTransformer会通过check_inverse?

python - 如何以 JSON 格式发送 POST 请求?

javascript - 如何将用户从没有 html/view 的页面重定向回来?

php - json_decode 和浮点值

python - 在 Python 中查找最接近特定值的列表项

python - 高速公路网络套接字超时后如何重新连接?

javascript - HTML5 localStorage 覆盖数据

javascript - 对 json 进行排序和模式匹配