Python之容器类Collections

容器类Collections

标签(空格分隔): Python进阶


  1. defaultdict
  2. counter
  3. deque
  4. namedtuple

defaultdict

defaultdict的作用是可以不用检查key是否存在,如果不存在可以直接创建。 而不像dict,会raise KeyError.

示例代码:

some_dict = {}
some_dict['colours'] = "yellow"
# Raises KeyError: 'colours'

示例代码2:

from collections import defaultdict
some_dict = defaultdict()
some_dict['colours'] = 'yellow'
#  it works

defaultdict的经典用法
示例代码3:

from collections import defaultdict

colours = (
    ('Yasoob', 'Yellow'),
    ('Ali', 'Blue'),
    ('Arham', 'Green'),
    ('Ali', 'Black'),
    ('Yasoob', 'Red'),
    ('Ahmed', 'Silver'),
)

favourite_colours = defaultdict(list)

for name, colour in colours:
    favourite_colours[name].append(colour)

Counter

Counter可以帮助计算一个iterable或者mapping中各个item的出现次数。

示例代码4:

from collections import Counter

colours = (
    ('Yasoob', 'Yellow'),
    ('Ali', 'Blue'),
    ('Arham', 'Green'),
    ('Ali', 'Black'),
    ('Yasoob', 'Red'),
    ('Ahmed', 'Silver'),
)

favs = Counter(name for name, colour in colours)
print(favs)
# Output: Counter({
#    'Yasoob': 2,
#    'Ali': 2,
#    'Arham': 1,
#    'Ahmed': 1
# })

deque

deque == double ended queue 双头队列
deque 可以从左/右 进元素和出元素。

示例代码5:

from collections import deque
d = deque()
d.append('1')
d.append('2')
d.append('3')
d.appendleft('4')
d
#output:  deque([4, 1, 2, 3])
d = deque(range(5))
print d
# output: deque([0, 1, 2, 3, 4])
d.pop()
#output: 4
d.popleft()
#output: 0
print d
#output:  deque([1,2,3])
d.extendleft([0])
d.extend([6,7,8])
print d
#output: deque([0, 1, 2, 3, 6, 7, 8])

namedtuple

tuple和list的区别就是tuple是不可变的,tuple在初始化好了之后,元素不能插入也不能删除.
而namedtuple也继承了不可变的性质,但是它有点像dict,元素是key-value形式的,也就是named的由来,在初始化之后,可以通过name来访问元素。

示例代码6:

from collections import namedtuple
#tuple_name  = namedtuple('tuple_name', 'item1_name, item2_name,...')
Animal = namedtuple('Animal', 'name age type')

perry = Animal(name="perry", age=31, type="cat")

print(perry)
# Output: Animal(name='perry', age=31, type='cat')

print(perry.name)
# Output: 'perry'

perry.age=40
# Output: Traceback (most recent call last):
#            File "", line 1, in
#         AttributeError: can't set attribute
posted @ 2016-11-28 15:10  geek精神  阅读(492)  评论(0编辑  收藏  举报