maple412 发表于 2014-12-31 11:36

关于字典

统计字符串中各个字符的个数,代码如下
def countWords(strLine):
    count={'alpha':0,'space':0,'digit':0,'others':0}
    length=len(strLine)
    for i in range(length):
      if strLine == '\n':
            break;
      if strLine.isdigit():
            count['digit']+=1
      elif strLine.isalpha():
            count['alpha']+=1
      elif strLine.isspace():
            count['space']+=1
      else:
            count['others']=length-count['digit']-count['alpha']-count['space']
    return {'alpha':count['alpha'],'space':count['space'],'digit':count['digit']

但是为什么执行后的字典顺序如下,和之前定位的时候的顺序不一样了呢?
{'alpha': 17, 'digit': 10, 'others': 5, 'space': 6}

icymirror 发表于 2014-12-31 12:47

你使用的count是map(也就是hashtable),他的显示顺序和你的赋值顺序没有什么太直接的关系。
但是系统的输出顺序是相对一致的。
你可以试下:
在初始化count之后,马上print count一下,
然后,在返回count之前,再print count一下。

周应侯 发表于 2014-12-31 14:17

dict本身就是无序的
页: [1]
查看完整版本: 关于字典