forked from eastlakeside/interpy-zh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12_collection.py
56 lines (45 loc) · 1.08 KB
/
12_collection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import collections, json
colours = (
('Yasoob', 'Yellow'),
('Ali', 'Blue'),
('Arham', 'Green'),
('Ali', 'Black'),
('Yasoob', 'Red'),
('Ahmed', 'Silver'),
)
def defaultdict_test():
favourite_colours = collections.defaultdict(list)
for name, colour in colours:
favourite_colours[name].append(colour)
print favourite_colours
def defaultdict_keyError():
tree = lambda: collections.defaultdict(tree)
some_dict = tree()
some_dict['colours']['favourite'] = 'yellow'
print json.dumps(some_dict)
def counter_test():
favs = collections.Counter(name for name, colour in colours)
print favs
def deque_test():
d = collections.deque()
d.append('1')
d.append('2')
d.append('3')
d.pop()
print d
d.popleft()
print d
def namedtuple_test():
Animal = collections.namedtuple('Animal', 'name age type')
perry = Animal(name='perry', age=31, type='cat')
print perry.name
print perry[0]
# perry.age = 21 This is wrong, you can't change it
def main():
defaultdict_test()
defaultdict_keyError()
counter_test()
deque_test()
namedtuple_test()
if __name__ == '__main__':
main()