반응형
카운터와 딕셔너리의 차이 in Python
예제 01)
- 딕셔너리와 랜덤 함수를 이용하여 딕셔너리의 밸류 생성하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import random
from collections import Counter
obj_list = ["A", "B", "C", "D", "E"]
dct = {}
for obj in obj_list:
dct[obj] = 0
for _ in range(100):
recv_obj = random.choice(obj_list)
dct[recv_obj] = dct[recv_obj] + 1
print(dct)
#### Result ####
{'A': 21, 'B': 19, 'C': 21, 'D': 18, 'E': 21}
|
cs |
예제 02)
- 카운터와 랜덤 함수를 이용하여 카운터의 밸류 생성하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import random
from collections import Counter
obj_list = ["A", "B", "C", "D", "E"]
counter = Counter()
for _ in range(100):
recv_obj = random.choice(obj_list)
counter[recv_obj] = counter[recv_obj] + 1
print(counter)
#### Result ####
Counter{'E': 23, 'A': 22, 'D': 21, 'B': 20, 'C': 14}
|
cs |
예제 03)
1
2
3
4
5
6
7
8
9
10
11
|
import random
from collections import Counter
obj_list = ["A", "B", "C", "D", "E"]
occurences = random.choice(obj_list, k=100)
print(occurences)
#### Result ####
['D', 'C', 'E', 'C' ... ]
|
cs |
예제 04)
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
|
import random
from collections import Counter
obj_list = ["A", "B", "C", "D", "E"]
occurences = random.choice(obj_list, k=100)
dct = {}
for obj in obj_list:
dct[obj] = 0
for occurence in occurences:
dct[occurence] += 1
counter = Counter(occurences)
print(counter)
print(dct)
#### Result ####
Counter({['E': 29, 'D': 24, 'C': 18, 'B': 18, 'A': 11})
{'A': 11, 'B': 18, 'C': 18, 'D': 24, 'E': 29}
|
cs |
예제 05)
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
|
import random
from collections import Counter
obj_list = ["A", "B", "C", "D", "E"]
occurences = random.choice(obj_list, k=100)
dct = {}
for obj in obj_list:
dct[obj] = 0
for occurence in occurences:
dct[occurence] += 1
counter = Counter(occurences)
print(counter.most_common()[:2])
print(dct)
#### Result ####
[('C': 24), ('D': 21)]
{'A': 11, 'B': 18, 'C': 18, 'D': 24, 'E': 29}
|
cs |
예제 06)
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
|
import random
from collections import Counter
obj_list = ["A", "B", "C", "D", "E"]
occurences = random.choice(obj_list, k=100)
dct = {}
for obj in obj_list:
dct[obj] = 0
for occurence in occurences:
dct[occurence] += 1
counter = Counter(occurences)
print(counter.most_common()[0])
print(dct)
max_val = -1
max_key = None
for key, value in dct.items():
if value > max_val:
max_key = key
print(max_key, max_val)
#### Result ####
('E': 28)
E 28
|
cs |
반응형
'공부 > 파이썬 Python' 카테고리의 다른 글
Python에서의 실제 콜센터 프로세스 시뮬레이션 (0) | 2022.03.23 |
---|---|
Python으로 전처리 파이프라인 설계하기 (3) | 2022.03.22 |
다항식 회귀 (Polynomial Regression)이란 (0) | 2022.03.19 |
칼로리 트래커 / 대시보드 (1) (0) | 2022.03.18 |
비밀번호 관리 매니저 만들기 using Python (0) | 2022.03.18 |
댓글