小发现

python的defaultdict

有很多以下的情景,你100%遇到过。看完这个例子,你肯定能知道defaultdict能用来做什么

# 统计items中每个元素的个数, 将其存到字典中, 元素为key, 个数为value
items = ["a", "b", "c", "d", "e", "a", "a", "b", "d"]
count = {}

# 方法一
for item in items:
    if item in count:
        count[item] += 1
    else:
        count[item] = 1

    print(count)

# 方法二
for item in items:
    count[item] = count.setdefault(item, 0) + 1
    # 使用setdefault, 已经存在就返回现有的value, 不存在的话就直接设置, 并返回设置的值

print(count)

# 方法三
from collections import defaultdict

count = defaultdict(int)
# 字典value的默认值为int类型, 也就是0

for item in items:
    count[item] += 1
    # 这样每次设置值, 就不用担心key是否存在了

print(count)

 线程安全与非线程安全

就是没有控制多个线程对同⼀资源的访问,对数据造成破 坏,使得线程运⾏的结果不可预期。这种现象称为“线程不安全”。

反之就是线程安全

posted @ 2019-10-01 18:15  王剑威  阅读(64)  评论(0)    收藏  举报