본문 바로가기
공부/파이썬 Python

카운터와 딕셔너리의 차이 in Python

by 혼밥맨 2022. 3. 20.
반응형

카운터와 딕셔너리의 차이 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)
28
cs

 

반응형

댓글