티스토리 뷰

🦖 Programming

[Python] count() 함수

박낑깡이 2022. 7. 5. 13:54

1. count() 함수

문자열 혹은 리스트 안에서 찾고 싶은 문자(혹은 문자열)의 개수를 찾아주는 함수

대소문자 구분 가능

카운팅하는 범위 지정 가능

 

 

 

1)  문자열에서의 사용

 

strLen = "HelloWorld!"
strLen.count("o")

 

=> 2

 

 

2) 리스트에서의 사용

 

lis = [2,5,6,2,7,8,5,6,2,1]
lis.count(2)

 

=> 3

 

 

3) 카운팅 범위 지정해주기

 

strLen = "HelloWorld!"
strLen.count("o",3,5)

 

=> 1

 

 

 

~응용~

백준 2577번

<숫자의 개수>

 

 

처음 내가 쓴 코드

 

a = int(input())
b = int(input())
c = int(input())
d = a * b * c
lis = []
x0 = 0
x1 = 0
x2 = 0
x3 = 0
x4 = 0
x5 = 0
x6 = 0
x7 = 0
x8 = 0 
x9 = 0 
for i in range(len(str(d))):
  if(str(d)[i] == '0'):
    x0 += 1;
  elif(str(d)[i] == '1'):
    x1 += 1;
  elif(str(d)[i] == '2'):
    x2 += 1;
  elif(str(d)[i] == '3'):
    x3 += 1;  
  elif(str(d)[i] == '4'):
    x4 += 1;  
  elif(str(d)[i] == '5'):
    x5 += 1;
  elif(str(d)[i] == '6'):
    x6 += 1;
  elif(str(d)[i] == '7'):
    x7 += 1;
  elif(str(d)[i] == '8'):
    x8 += 1;
  else:
    x9 += 1;

print(x0)
print(x1)
print(x2)
print(x3)
print(x4)
print(x5)
print(x6)
print(x7)
print(x8)
print(x9)

 

머리가 나쁘면...손발이 고생....

 

 

count()함수를 이용해 다시 쓴 코드

 

a = int(input())
b = int(input())
c = int(input())
res = str(a*b*c)
for i in range(10):
  print(res.count(str(i)))

 

 

댓글
최근에 올라온 글
«   2024/09   »
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
Total
Today
Yesterday