요소가 숫자인 목록이 있습니다. 많은 요소가 여러 번 나타납니다. 요소 자체와 함께 각 요소의 빈도가 있도록 하위 목록을 만들고 싶습니다.
for 및 추가 사용
이 접근 방식에서 우리는 목록의 각 요소를 그 뒤에 있는 다른 모든 요소와 비교할 것입니다. 일치하는 항목이 있으면 개수가 증가하고 요소와 개수가 모두 존재하게 됩니다. 모든 요소와 빈도를 보여주는 하위 항목을 포함해야 하는 목록이 만들어집니다.
예시
def occurrences(list_in):
for i in range(0, len(listA)):
a = 0
row = []
if i not in listB:
for j in range(0, len(listA)):
# matching items from both positions
if listA[i] == listA[j]:
a = a + 1
row.append(listA[i])
row.append(a)
listB.append(row)
# Eliminate repetitive list items
for j in listB:
if j not in list_uniq:
list_uniq.append(j)
return list_uniq
# Caller code
listA = [13,65,78,13,12,13,65]
listB = []
list_uniq = []
print("Number of occurrences of each element in the list:\n")
print(occurrences(listA)) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
Number of occurrences of each element in the list: [[13, 3], [65, 2], [78, 1], [12, 1]]
카운터 포함
우리는 컬렉션 모듈의 카운터 메서드를 사용합니다. 목록의 모든 요소 수를 알려줍니다. 그런 다음 새로운 빈 목록을 선언하고 각 항목에 대한 키 값 쌍을 요소 형식으로 추가하고 해당 개수를 새 목록에 추가합니다.
예시
from collections import Counter
def occurrences(list_in):
c = Counter(listA)
new_list = []
for k, v in c.items():
new_list.append([k, v])
return new_list
listA = [13,65,78,13,12,13,65]
print("Number of occurrences of each element in the list:\n")
print(occurrences(listA)) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
Number of occurrences of each element in the list: [[13, 3], [65, 2], [78, 1], [12, 1]]