이 튜토리얼에서는 배열에 있는 모든 요소의 빈도를 찾는 프로그램을 작성할 것입니다. 다양한 방법으로 찾을 수 있습니다. 그 중 두 가지를 살펴보겠습니다.
딕셔너리 사용
-
배열을 초기화합니다.
-
빈 dict 초기화 .
-
목록을 반복합니다.
-
요소가 사전에 없으면 값을 1로 설정합니다. .
-
그렇지 않으면 값을 1 증가시킵니다. .
-
-
dict를 반복하여 요소와 빈도를 인쇄합니다.
예
코드를 봅시다.
# intializing the list
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# initializing dict to store frequency of each element
elements_count = {}
# iterating over the elements for frequency
for element in arr:
# checking whether it is in the dict or not
if element in elements_count:
# incerementing the count by 1
elements_count[element] += 1
else:
# setting the count to 1
elements_count[element] = 1
# printing the elements frequencies
for key, value in elements_count.items():
print(f"{key}: {value}") 출력
위의 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.
1: 3 2: 4 3: 5
Collections 모듈의 Counter 클래스를 사용하는 두 번째 접근 방식을 살펴보겠습니다.
카운터 클래스 사용
-
컬렉션 가져오기 모듈.
-
배열을 초기화합니다.
-
목록을 카운터에 전달 수업. 그리고 결과를 변수에 저장합니다.
-
결과를 반복하여 요소와 빈도를 인쇄합니다.
예
아래 코드를 참조하세요.
# importing the collections module
import collections
# intializing the arr
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# getting the elements frequencies using Counter class
elements_count = collections.Counter(arr)
# printing the element and the frequency
for key, value in elements_count.items():
print(f"{key}: {value}") 출력
위의 코드를 실행하면 이전과 같은 결과를 얻을 수 있습니다.
1: 3 2: 4 3: 5
결론
튜토리얼에 의문점이 있으면 댓글 섹션에 언급하세요.