Python标准库

如果一个模块已经被引用了,Python可以做到不再次进行引用

setdefault()&defaultdict()

d.setdefault(key, defaultvalue)
# 如果键不存在字典中,则会被赋予默认值。否则不会改变原有的键值

from collection import defaultdict
defaultdict(fun)
# 以函数作为参数,它返回赋给缺失的键值
# e.g.
from collections import defaultdict
dic = defaultdict(int)
print(dic['d']) # 0

# 可以搭配lambda来赋予初始值
defaultdict(lambda: 'no-value')

Counter

以一个列表作为参数,返回一个Counter对象,其内部是{元素: 元素在列表中出现次数},e.g.

from collections import Counter
example_list = ['a', 'b', 'a', 'c']
Counter(example_list) # 返回Counter({'a': 2, 'b': 1, 'c': 1})

Counter支持一些类似集合的运算:

from collections import Counter
example_list1 = ['a', 'b', 'a', 'c']
example_list2 = ['a', 'a', 'a', 'b']

# + 计数器相加
Counter(example_list1) + Counter(example_list2)
# Counter({'a': 5, 'b': 2, 'c': 1})

# - 第一个计数器有,而第二个没有的元素
Counter(example_list1) - Counter(example_list2) 
# Counter({'c': 1})

# & 交集,取两者共有的项的较小计数
Counter(example_list1) & Counter(example_list2)
# Counter({'a': 2, 'b': 1})

# | 并集,相同的元素则取较大的计数
Counter(example_list1) | Counter(example_list2)
# Counter({'a': 3, 'b': 1, 'c': 1})

OrderedDict()

有序字典,记忆字典键添加的顺序,然后从一个迭代器按照相同的顺序返回。e.g.

from collections import OrderedDict
example_dict = {
  'a': 1,
  'b': 2,
  'c': 3
}

for key in OrderedDict(example_dict):
    print(key)
# a
# b
# c

deque双端队列

from collections import deque

传入一个序列,返回一个双端队列。

  • popleft() 可去掉最左边的项并返回该项
  • pop() 去掉最右边的项并返回该项
  • append()
  • appendleft() 把元素加在左边

  • rotate() 队列的旋转操作

rotate参数为正时,由队列尾开始往前,依次把元素移动到队列首部,直到移动参数数目的元素; rotate参数为负时,由队列首开始往后,依次把元素移动到队列尾部,直到移动参数数目的元素

from collections import deque

d = deque(range(5))
print(d) # deque([0, 1, 2, 3, 4])
d.rotate(2)
print(d) # deque([3, 4, 0, 1, 2])
d.rotate(5)
print(d) # deque([3, 4, 0, 1, 2]) 当参数大于等于列表长度的时候则无效

d2 = deque(range(5))
print(d2) # deque([0, 1, 2, 3, 4])
d2.rotate(-2)
print(d2) # deque([2, 3, 4, 0, 1])
d2.rotate(-5)
print(d2) # deque([2, 3, 4, 0, 1]) 当参数的绝对值大于等于列表长度的时候则无效

可以通过关键字参数maxlen来限制一个双端数列的大小

d = deque(maxlen=30)

namedtuple

命名元组。通过命名元组创建的对象具有元祖的特性,而且可以通过位置索引&键值索引获取到元组内的数据。

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])

p = Point(1, 2)
print(p) # Point(x=1, y=2)
p.x # 1
p.y # 2
p[0], p[1] # (1, 2)
x, y = p
x, y # (1, 2)

itertools迭代代码结构

import itertools

# itertools.chain(list1, list2....) 将多个列表进行迭代
for item in itertools.chain([1, 2], ['a', 'b', 'c']):
    print(item)
# 1
# 2
# a
# b
# c

# itertools.cycle() 在传入的参数间无限迭代
for item in itertools.cycle([1, 2]):
    print(item)
# 1
# 2
# 1
# 2
# ....

# itertools.accumulate() 计算累积的值。默认情况下累加。也可以传入一个函数作为第二个参数,该函数必须接受两个参数,返回单个结果
for item in itertools.accumulate([1, 2, 3, 4]):
    print(item)
# 1
# 3
# 6
# 10

for item in itertools.accumulate([1, 2, 3, 4], lambda a, b: a * b):
    print(item)
# 1
# 2
# 6
# 24

results matching ""

    No results matching ""