Home Data Structures
Post
Cancel

Data Structures

Stack

1
2
3
4
5
6
7
stk = []
stk.append(0)
stk.append(1)
stk.append(2)
print(stk)
stk.pop()
print(stk)
[0, 1, 2]
[0, 1]

Queue

1
2
3
4
5
6
7
q = []
q.append(1)
q.append(2)
q.append(3)
print(q)
q.pop(0)
print(q)
[1, 2, 3]
[2, 3]

Set

1
2
s = set([1,2,3])
s2 = {4,5,6,6}
1
2
s.add(4)
print(s)
{1, 2, 3, 4}
1
2
s.remove(4)
print(s)
{1, 2, 3}
1
2
s.update([5])
print(s)
{1, 2, 3, 5}
1
2
s.discard(5)
print(s)
{1, 2, 3}
1
2
3
4
5
6
7
8
s1 = set([1,2,3])
s2 = set([2,3,4])
print(s1.union(s2))
print(s1 | s2)
print(s1.intersection(s2))
print(s1 & s2)
print(s1.difference(s2))
print(s1 - s2)
{1, 2, 3, 4}
{1, 2, 3, 4}
{2, 3}
{2, 3}
{1}
{1}

Dict

1
d = {'jason':82, 'marry':17, 'jon':32}
1
2
3
print(d.items())
for e in d.items():
    print(e, end=" ")
dict_items([('jason', 82), ('marry', 17), ('jon', 32)])
('jason', 82) ('marry', 17) ('jon', 32) 
1
2
for key in d.keys():
    print(d[key], end=" ")
82 17 32 
1
2
d.pop('jason')
print(d)
{'marry': 17, 'jon': 32}
1
2
3
4
5
d['jason'] = 82
print(d)

d.popitem()
print(d)
{'marry': 17, 'jon': 32, 'jason': 82}
{'marry': 17, 'jon': 32}
1
2
d.popitem()
print(d)
{'marry': 17}

collections module

1
2
3
4
5
from collections import deque
from collections import Counter
from collections import OrderedDict
from collections import defaultdict
from collections import namedtuple

deque

1
2
3
4
5
6
7
8
9
10
deq = deque()
deq.append(1)
deq.append(2)
print(deq)
deq.appendleft(3)
print(deq)
deq.pop()
print(deq)
deq.popleft()
print(deq)
deque([1, 2])
deque([3, 1, 2])
deque([3, 1])
deque([1])
1
2
3
deq.append(3)
deq.appendleft(2)
print(deq)
deque([2, 1, 3])
1
2
deq.rotate(2)
print(deq)
deque([2, 1, 3])
1
2
3
4
print(deq)
deq.extend([1])
deq.extend([1,2,3])
print(deq)
deque([2, 1, 3])
deque([2, 1, 3, 1, 1, 2, 3])

OrderedDict (obselete)

1
2
3
4
5
6
7
8
9
d = OrderedDict({'jason':82, 'zarry':17, 'aon':32})
d2 = {'jason':82, 'zarry':17, 'aon':32}

for k,v in d.items():
    print(k,v)

print('*'*10)
for k,v in d2.items():
    print(k,v)
jason 82
zarry 17
aon 32
**********
jason 82
zarry 17
aon 32

defaultdict

frequency 사용할때도 유용함

1
d = defaultdict(lambda: 0) # default (기본값) 설정
1
d['first'] # 아무것도 없는데 설정됨
0

Counter

-> set 연산도 가능

1
2
c = Counter()
c
Counter()
1
2
c = Counter('sadfasdwlefw') # dictionary 반환
c
Counter({'s': 2, 'a': 2, 'd': 2, 'f': 2, 'w': 2, 'l': 1, 'e': 1})
1
2
c = Counter({'a' : 2, 'b' : 3, 'c' : 6})
list(c.elements())
['a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c']

namedtuple

1
2
3
4
Point = namedtuple('Point', ['x','y'])
p = Point(x=11, y=22)
print(p[0], p[1])
print(p.x, p.y)
11 22
11 22
1
p.x, p.y
This post is licensed under CC BY 4.0 by the author.
Trending Tags