dequeue、defaultdict、Counter

dequeue

  • 比较方便的解决了频繁删除插入带来的效率问题
from collections import deque

q = deque(['a','b','c'])
print(q)

q.append("d")
print(q)

q.appendleft("x")
print(q)
deque(['a', 'b', 'c'])
deque(['a', 'b', 'c', 'd'])
deque(['x', 'a', 'b', 'c', 'd'])

defaultdict

  • 当直接读取dict不存在的属性时,直接返回默认值
d1 = {"one":1,"two":2,"three":3}
print(d1['one'])
print(d1['four'])
1
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-83-bff241983722> in <module>
      1 d1 = {"one":1,"two":2,"three":3}
      2 print(d1['one'])
----> 3 print(d1['four'])
KeyError: 'four'
from collections import defaultdict

# lambda表达式,直接返回字符串
func = lambda:"wcp"
d2 = defaultdict(func)

d2["one"] = 1
d2["two"] = 2

print(d2['one'])
print(d2['four'])

print(d2)
1
wcp
defaultdict(<function <lambda> at 0x00000251F3080510>, {'one': 1, 'two': 2, 'four': 'wcp'})

Counter

  • 统计字符串个数
from collections import Counter

# 括号里的内容是可迭代的
c = Counter("sjdfhgdfhsaidjfjkashfoiffjsabfiaus")
print(c)
Counter({'f': 7, 's': 5, 'j': 4, 'a': 4, 'd': 3, 'h': 3, 'i': 3, 'g': 1, 'k': 1, 'o': 1, 'b': 1, 'u': 1})
s = ["wcp","abc","abc","abc","abc","ppt","ttp"]
c = Counter(s)

print(c)
Counter({'abc': 4, 'wcp': 1, 'ppt': 1, 'ttp': 1})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值