Trip to Python

리스트 원소를 어떻게 변경할 것인가?

Kestrel 2022. 11. 22. 22:26

파이썬을 정복하기 위해서 온라인 강의를 듣고 있는데 처음으로 막혔던 부분이다.

리스트 원소를 바꾸는 방법은 앞으로도 유용하게 쓰일 수 있을 것 같아서 기록으로 남겨둔다.

아래는 강의 주제 중 행맨을 구현하는 과정에서 나온 것이다.

 

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)

 

1) 먼저 단어 리스트를 생성하고 1개의 단어를 리스트에서 무작위 추출한다. 실제 행맨 게임을 만든다면 리스트의 원소 양이 훨씬 많을 것이다.

 

#Testing code
print(f'Pssst, the solution is {chosen_word}.')

 

2) 이것은 잘되어가고 있나 확인용 코드

#TODO-1: - Create an empty List called display.
#For each letter in the chosen_word, add a "_" to 'display'.
#So if the chosen_word was "apple", display should be ["_", "_", "_", "_", "_"] with 5 "_" representing each letter to guess

 

.
display = []
word_length = len(chosen_word)
for _ in range(word_length):
    display += "_"

 

3) display라는 빈 리스트를 만들고 단어의 캐릭터 수를 말해주는 len 함수를 통해서 캐릭터 수를 확인하고 그 만큼 _ 를 만들어 준다. 참 반복 작업을 해주는 for 문이 이해는 되지만 마음처럼 쓰기에는 참 어렵다.

guess = input("Guess a letter: ").lower()

 

4) 대소문자 구분이 되기 때문에 타이핑되는 캐릭터를 모두 소문자로 바꿔 입력 시 오류가 뜨지 않도록 한다.

#TODO-2: - Loop through each position in the chosen_word;
#If the letter at that position matches 'guess' then reveal that letter in the display at that position.
#e.g. If the user guessed "p" and the chosen word was "apple", then display should be ["_", "p", "p", "_", "_"].

 

for position in range(word_length):

5-1) for문을 생성해 각 단어의 캐릭터로 접근하기 위한 설정을한다. 캐릭터 수는 변동이 되므로 길이 측정 함수를 변수로 입력.
    letter = chosen_word[position]

5-2) 오른쪽 편을 보면 선택된 캐릭터 하나하나에 접근하여 letter 변수에 차례대로 넣는다. chosen_word[0] 이고 선택된 단어가 camel이면 c가 들어간다. 그렇게 차례대로 c, a, m, e, l이 letter로 들어간다. 나에게 너무 어려웠던 부분으로 새로운 변수에 차례대로 선택된 단어의 캐릭터를 집어 넣어주는 방식으로 위치 값 부여하는 것 떠올리기 어려웠다. 지금 글을 쓰다보니 인덱스에 활용이 익숙하지 않아서 떠올리기 어려웠던 것 같다.  #print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
    if letter == guess:

5-3) 그리고 처음 유저가 추측한 캐릭터와 차례대로 추출된 letter의 원소들과 동일한지 확인한다.맞으면 
        display[position] = letter

5-4) 해당 위치의 _를 해당 캐릭터로 바꿔준다.

 

5) 세세한 해설 듣기 전까지는 이해가 너무 안되었던 부분으로 맞는 부분을 _ 대신 맞는 단어로 대치하는 코드로 특히나 letter 변수 처리하는 부분이 이해가 안되었다. 라인 하나하나 마다 코멘트롤 달아 이해도를 높여보겠다.

 

6) 여기서 어려웠던 점은 정답 캐릭터와 추측 캐릭터의 일치 여부를 따지는 동시에 해당 위치를 찾아내고 일치 여부에 따라 캐릭터를 변경해주는 것을 어떻게 코드로 구현할 것인지가 문제였다.

#TODO-3: - Print 'display' and you should see the guessed letter in the correct position and every other letter replace with "_".
#Hint - Don't worry about getting the user to guess the next letter. We'll tackle that in step 3.
print(display)