Python——容器和枚举

给你一囗甜甜゛ 提交于 2020-01-25 00:54:32

容器 Collections

Python附带的一个模块,包含许多容器数据类型。

defaultdict

dict不同,不需要检查key是否存在

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)

print(favourite_colours)
"""
defaultdict(<class 'list'>, {'Yasoob': ['Yellow', 'Red'], 'Ali': ['Blue', 'Black'], 'Arham': ['Green'], 'Ahmed': ['Silver']})
"""

当你在一个字典中对一个键进行嵌套赋值时,如果这个键不存在,就会触发keyError异常,允许我们使用另外的一种方式绕过这个问题。

some_dict = {}
some_dict['colours']['favourite'] = "yellow"
# 异常输出:KeyError: 'colours'

你可以使用的解决方案:

import collections
import json
tree = lambda : collections.defaultdict(tree)
some_dict = tree()
some_dict['colours']['favourite'] = "yellow"
print(json.dumps(some_dict))

counter

Counter是一个计数器,可以帮助我们针对某项数据进行计数。

from collections import Counter

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

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

deque

deque提供了一种双端队列,你可以从头/尾两端添加或删除元素,如果想要使用它,首先我们从collections中导入deque模块。

from collections import  deque
d = deque()
d.append(1)
print(d)
d.append(2)
print(d)
d.append(3)
print(d)
"""
deque([1])
deque([1, 2])
deque([1, 2, 3])
"""

从两端取出pop数据

from collections import deque

d = deque(range(5))
print(len(d))
print(d)
d.popleft()
print(d)
d.pop()
print(d)
"""
5
deque([0, 1, 2, 3, 4])
deque([1, 2, 3, 4])
deque([1, 2, 3])
"""

你也可以限制这个列表的大小,当你超出设定的限制时,数据就会从另一个端挤出去。

d = deque(maxlen = 30)

当你插入的数据超过限定的时候,最左边一端的数据从队列中删除。

你也可以从任一端扩展这个队列

from collections import deque
d = deque(maxlen=10)

d = deque([1,2,3,4,5])
d.extendleft([0])
d.extend([6,7,8])
print(d)
"""
deque([0, 1, 2, 3, 4, 5, 6, 7, 8])
"""

namedtuple

一个元组时一个不可变的元素,你可以存储一个数据的序列,它和命名元组非常像,但是有几个关键的不同。

主要相似点是都不像列表,你不能修改元组中的数据。为了获取元组中的数据,你需要使用整数作为索引。

man = ('Ali', 30)
print(man[0])
" Ali

namedtuples可以把元组编程一个针对简单任务的容器,你不必使用整数索引来访问一个namedtuple的数据。你可以像字典一样访问,但是是不可变的。

from collections import namedtuple

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

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

你可以用名称来访问namedtuple中的数据,一个命名元组有两个必须的参数,是元组的名称和字段名称。而且每个实例没有对象字典,所以很轻量,与普通元组比,并不需要更多的内存,这使得它们比字典更快。

from collections import namedtuple

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

print(perry._asdict())
# rderedDict([('name', 'perry'), ('age', 31), ('type', 'cat')])

也可以将一个命名元组转换为字典。

Enum

枚举对象

from collections import namedtuple
from enum import Enum
class Species(Enum):
    cat = 1
    dog = 2
    horse = 3
    aardvark = 4
    butterfly = 5
    owl = 6
    platypus = 7
    dragon = 8
    unicorn = 9
    kitten = 1  
    puppy = 2   
Animal = namedtuple('Animal', 'name age type')
perry = Animal(name="Perry", age=31, type=Species.cat)
drogon = Animal(name="Drogon", age=4, type=Species.dragon)
tom = Animal(name="Tom", age=75, type=Species.cat)
charlie = Animal(name="Charlie", age=2, type=Species.kitten)

print(charlie.type == tom.type)

枚举

枚举是Python内置函数,它与我们遍历数据并自动计数。

my_list = ['apple', 'banana', 'grapes', 'pear']
for c , value in enumerate(my_list, 1):
    print(c, value)
"""
1 apple
2 banana
3 grapes
4 pear
"""
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!