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

8 投票
1 回答
3058 浏览
提问于 2025-04-17 02:25

我有一串用逗号分隔的数字。其实我可以搜索并统计大部分数字的出现次数,特别是两位数的数字。

比如说,如果我有这样的数字序列:

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)

1 个回答

8

在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),因为它会对每一个不同的数字都遍历一遍数字列表。

撰写回答