Skip to content

Commit e725bc8

Browse files
add collections examples
1 parent 408c48f commit e725bc8

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

collections_examples.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from collections import Counter
2+
from collections import namedtuple
3+
from collections import defaultdict
4+
5+
my_list = [1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 3, 'a', 'abc', "fish"]
6+
print(Counter(my_list))
7+
8+
sentence = "This is a super cool sentence, how cool is this?"
9+
print(Counter(sentence.split()))
10+
11+
letters = "aaaaaaaabbbbbbbcccccdddddddd"
12+
c = Counter(letters)
13+
print(c.most_common())
14+
print(c.most_common(2))
15+
print(list(c))
16+
17+
d = {'a': 10}
18+
print(d['a'])
19+
# print(d['WRONG_KEY']) # this will throw a key error
20+
d = defaultdict(lambda: 0)
21+
d['correct_key'] = 100
22+
print(d['correct_key'])
23+
print(d['wrong_key']) # this will get the default value instead of throwing a key error
24+
25+
26+
my_tuple = (10,20,30)
27+
print(my_tuple[0])
28+
29+
Dog = namedtuple('Dog', ['age', 'breed', 'name'])
30+
sammy = Dog(age=5, breed='Husky', name='Sam')
31+
print(type(sammy))
32+
print(sammy)
33+
print(sammy[0])
34+
print(sammy[1])
35+
print(sammy[2])
36+

0 commit comments

Comments
 (0)