python - 对出现字符串的计数,四种方法,第三种不知道怎么不行
大家讲道理
大家讲道理 2017-05-18 10:52:38
[Python讨论组]
import os
import json
os.chdir("F:\\pydata-book-master\\ch02")
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]


# method1
def get_counts(sequence):
    counts={}
    for x in sequence:
        if x in counts:
            print(x)
            print(counts)
            counts[x]+=1
        else:
            counts[x]=1
    return counts

#######################################

# method2
from collections import defaultdict
def get_counts2(sequence):
    counts=defaultdict(int)
    for x in sequence:
        counts[x]+=1
    return counts
print(get_counts2(time_zones))
##########################################


# method3
from collections import defaultdict
def get_counts2(sequence):
    counts={}
    for x in sequence:
        counts[x]+=1
    return counts
print(get_counts2(time_zones))

##########################################

# method4
from collections import Counter
counts=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)
PHPz

method3中的用法, 触发了KeyError异常, 因为你在没有初始化值的情况下, 直接就counts[x]+=1, 这样它压根找到之前没定义过的key, 就更别说+1, 你只是import defaultdict, 却没用上, 导致实际上逻辑和method1一样, 所以,解决的方法,就是method1

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号