国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

python - 對(duì)出現(xiàn)字符串的計(jì)數(shù),四種方法,第三種不知道怎么不行

瀏覽:109日期:2022-07-15 18:37:26

問題描述

import osimport jsonos.chdir('F:pydata-book-masterch02')path=’usagov_bitly_data2012-03-16-1331923249.txt’open(path).readline()records=[json.loads(line) for line in open(path) ]time_zones=[rec[’tz’] for rec in records if ’tz’ in rec]# method1def get_counts(sequence): counts={} for x in sequence:if x in counts: print(x) print(counts) counts[x]+=1else: counts[x]=1 return counts######################################## method2from collections import defaultdictdef get_counts2(sequence): counts=defaultdict(int) for x in sequence:counts[x]+=1 return countsprint(get_counts2(time_zones))########################################### method3from collections import defaultdictdef get_counts2(sequence): counts={} for x in sequence:counts[x]+=1 return countsprint(get_counts2(time_zones))########################################### method4from collections import Countercounts=Counter(time_zones)print(counts)# error of method3---------------------------------------------------------------------------KeyError Traceback (most recent call last)<ipython-input-7-cce65f8fc4d0> in <module>() 40 counts[x]+=1 41 return counts---> 42 print(get_counts2(time_zones)) 43 44 ##########################################<ipython-input-7-cce65f8fc4d0> in get_counts2(sequence) 38 counts={} 39 for x in sequence:---> 40 counts[x]+=1 41 return counts 42 print(get_counts2(time_zones))KeyError: ’America/New_York’

問題解答

回答1:

method3中的用法, 觸發(fā)了KeyError異常, 因?yàn)槟阍跊]有初始化值的情況下, 直接就counts[x]+=1, 這樣它壓根找到之前沒定義過的key, 就更別說+1, 你只是import defaultdict, 卻沒用上, 導(dǎo)致實(shí)際上邏輯和method1一樣, 所以,解決的方法,就是method1

標(biāo)簽: Python 編程
主站蜘蛛池模板: 彝良县| 巴林右旗| 彩票| 万源市| 探索| 会同县| 中宁县| 乌拉特中旗| 蓝山县| 体育| 凉城县| 泽普县| 卢氏县| 天台县| 汶上县| 鄂伦春自治旗| 全椒县| 沙雅县| 海兴县| 迁安市| 尼玛县| 山阴县| 闵行区| 神木县| 云龙县| 揭东县| 县级市| 甘洛县| 宜兰市| 临邑县| 黎城县| 晋江市| 石棉县| 长岛县| 宜州市| 和顺县| 邵武市| 潮安县| 余姚市| 隆昌县| 达日县|