[파이썬] 리스트 count 예제

count() 메서드는 리스트 내에서 특정 값이 나타나는 횟수를 세는 데 사용됩니다. 아래 예제를 통해 count() 메서드의 활용을 살펴보겠습니다:

numbers = [1, 2, 3, 4, 1, 5, 1, 6, 7, 1]

# 숫자 1이 리스트 내에서 몇 번 나타나는지 카운트
count_of_ones = numbers.count(1)
print(f"The count of 1s in the list: {count_of_ones}")  # 출력: The count of 1s in the list: 4

fruits = ["apple", "banana", "apple", "grape", "kiwi", "apple"]

# 문자열 "apple"이 리스트 내에서 몇 번 나타나는지 카운트
count_of_apples = fruits.count("apple")
print(f"The count of 'apple's in the list: {count_of_apples}")  # 출력: The count of 'apple's in the list: 3

text = "Hello, how are you?"

# 문자열 "o"가 텍스트 내에서 몇 번 나타나는지 카운트 (대소문자 구분)
count_of_o = text.count("o")
print(f"The count of 'o's in the text: {count_of_o}")  # 출력: The count of 'o's in the text: 2

count() 메서드를 사용하면 리스트나 문자열 내에서 특정 값이나 문자가 얼마나 자주 나타나는지 효과적으로 확인할 수 있습니다.