-
[python] dict 연습 - 단어(문장)에서 모음 찾기코딩 연습/코딩배우기 2020. 10. 8. 22:34반응형
■ [dict 연습] 단어, 문장에서 영어 모음 찾기
vowels = ['a', 'e', 'i', 'o', 'u'] word = input('Provides a word to search for vowels: ') found = [] found_dict = {} for kv in vowels: found_dict[kv] = 0 # dict 0으로 초기화 for letter in word: if letter in vowels: if letter not in found: # found list에 철자가 없으면 found.append(letter) found_dict[letter] += 1 # 철자 맞으면 1 증가 # 입력한 단어, 문장의 모음 리스트 print( 'vowels in the word that you provided:', end=' ') # 'end='로 연결 for vowel in found: print(vowel, end=', ') # dict 출력 방법 print('\n\n-- key에 맞는 value 출력 --') for k in found_dict: print(k, 'was found', found_dict[k], 'time(s)') print('\n\n-- 내장함수 sorted 사용 --') for k in sorted(found_dict): print(k, 'was found', found_dict[k], 'time(s)') print('\n\n-- items() 키/값 목록 반환 --') for k, v in found_dict.items(): # sorted(found_dict.items()) print(k, 'was found', v, 'item(s)') [실행 결과] Provides a word to search for vowels: If you want to be happy vowels in the word that you provided: o, u, a, e, -- key에 맞는 value 출력 -- a was found 2 time(s) e was found 1 time(s) i was found 0 time(s) o was found 2 time(s) u was found 1 time(s) -- 내장함수 sorted 사용 -- a was found 2 time(s) e was found 1 time(s) i was found 0 time(s) o was found 2 time(s) u was found 1 time(s) -- items() 키/값 목록 반환 -- a was found 2 item(s) e was found 1 item(s) i was found 0 item(s) o was found 2 item(s) u was found 1 item(s)
# dict 초기화 시키기 fruits = {} while True: word = input('insert fruits name: ') if word == 'exit': break # dict 초기화 시키기 : in 사용 # if word in fruits: # fruits[word] += 1 # else: # fruits[word] = 1 # dict 메서드 setdefault( , ) 사용 fruits.setdefault(word, 0) # 필요시 0 초기화 fruits[word] += 1 for fruit, num in fruits.items(): print('{} = {}개'.format(fruit, fruits[fruit]))
[참고] Head First Python
반응형'코딩 연습 > 코딩배우기' 카테고리의 다른 글
[python] 파이썬 예외처리 (0) 2020.10.11 [python] 파이썬 데이터 분석 입문 - 리스트, 튜플, 딕셔너리 (0) 2020.10.09 [python] 파이썬에서 환경 변수 읽어오기, 현재 작업 디렉토리 등 (0) 2020.10.08 [python] 파이썬 정규 표현식 (regular expression) (0) 2020.09.27 [python] 파이썬 문자열 관련 함수들 (0) 2020.09.27