久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

python - 對出現字符串的計數,四種方法,第三種不知道怎么不行

瀏覽:125日期: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中的用法, 觸發了KeyError異常, 因為你在沒有初始化值的情況下, 直接就counts[x]+=1, 這樣它壓根找到之前沒定義過的key, 就更別說+1, 你只是import defaultdict, 卻沒用上, 導致實際上邏輯和method1一樣, 所以,解決的方法,就是method1

標簽: Python 編程
主站蜘蛛池模板: 萨嘎县| 汝城县| 庆元县| 东乡| 鸡东县| 常山县| 巴楚县| 伊金霍洛旗| 三亚市| 东阳市| 沾益县| 洪泽县| 治多县| 灵璧县| 留坝县| 大宁县| 益阳市| 拉萨市| 綦江县| 康马县| 东乌| 苏尼特左旗| 稻城县| 仁寿县| 屯门区| 临猗县| 白山市| 康保县| 宿迁市| 尚义县| 舟曲县| 德阳市| 大余县| 鹤岗市| 新泰市| 当阳市| 太原市| 弥勒县| 西平县| 伊吾县| 荆州市|