我有一长串用逗号分隔的数字。我可以搜索和计算大多数数字(更准确地说是两位数),出现的次数。
例如,如果我的数字序列如下:
然而,由于它在
有没有人知道如何让以下代码仅匹配整个“字符串”?
例如,如果我的数字序列如下:
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)
Counter
是 2.7+,就像我说的一样(也许是你看过之后我添加的),但defaultdict
的替代品是 2.5+。 - agfsortedString = sorted(numcount,key = operator.itemgetter(1),reverse = True)
,但我收到一个错误,说“全局名称'operator'未定义”,即使我已经导入了from operator import itemgetter
。有什么帮助吗?谢谢。 - eoinzyJSON
,我尝试在json.dumps
代码中对其进行排序,但是sort_keys=true
只按左侧的数字排序,而不是按频率排序:outputString+=json.dumps({num: numcount[num]},sort_keys=True,indent=4)+","
。 - eoinzynumcount.iteritems()
,而不仅仅是使用numcount
,否则你只会得到键而不是键和值。如果你使用from operator import itemgetter
,那么你只需要使用key=itemgetter(1)
。如果你使用import operator
,那么你需要使用key=operator.itemgetter(1)
。 - agf