티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How do I count the occurrences of a list item?
리스트 아이템의 발생 카운트는 어떻게 계산합니까?
문제 내용
Given a single item, how do I count occurrences of it in a list, in Python?
단일 아이템이 주어지면, 파이썬 리스트에서 발생 카운트를 어떻게 셀 수 있나요?
A related but different problem is counting occurrences of each different element in a collection, getting a dictionary or list as a histogram result instead of a single integer. For that problem, see Using a dictionary to count the items in a list.
관련이 있지만 다른 문제는 컬렉션에서 서로 다른 각 아이템의 카운트를 계산하여 단일 정수 대신 히스토그램 결과로 사전 또는 목록을 가져오는 것입니다. 해당 문제에 대해서는 딕셔너리를 사용하여 리스트의 아이템 카운트 계산을 참조하세요.
높은 점수를 받은 Solution
If you only want a single item's count, use the count
method:
단일 아이템의 카운트만 원하는 경우 count 함수를 사용합니다.
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
Important: this is very slow if you are counting multiple different items
중요: 여러 항목을 세는 경우 이 속도가 매우 느립니다.
Each count
call goes over the entire list of n
elements. Calling count
in a loop n
times means n * n
total checks, which can be catastrophic for performance.
각 count 호출은 n개 아이템의 전체 리스트를 통과합니다. 호출 횟수가 n회인 경우 n회 *n회 총 점검 횟수를 의미하며, 이는 성능에 치명적일 수 있습니다.
If you want to count multiple items, use Counter
, which only does n
total checks.
여러 항목을 카운트하려면 합계 검사만 수행하는 Counter를 사용하십시오.
가장 최근 달린 Solution
mot = ["compte", "france", "zied"]
lst = ["compte", "france", "france", "france", "france"]
dict((x, lst.count(x)) for x in set(mot))
this gives
이것으로 알 수 있습니다.
{'compte': 1, 'france': 4, 'zied': 0}
출처 : https://stackoverflow.com/questions/2600191/how-do-i-count-the-occurrences-of-a-list-item
'개발 > 파이썬' 카테고리의 다른 글
list.join(string)이 아닌 string.join(list)인 이유 (0) | 2022.12.11 |
---|---|
딕셔너리 매핑 반전(키<->값)하기 (0) | 2022.12.11 |
현재 실행 중인 파일의 경로와 이름 가져오기 (0) | 2022.12.10 |
인덱스로 리스트에서 아이템 제거하기 (0) | 2022.12.10 |
파이썬 딕트에서 'has_key()'와 'in' 중 더 좋은 방법은? (0) | 2022.12.10 |