1. 리스트
- 파이썬에서는 기본 데이터 타입인 숫자형 타입, 불리언 타입, 문자열 타입과는 별도로 이들로 구성되는 다양한 컨테이너 형태의 데이터 구조를 제공합니다.
- 그 중에서도 가장 많이 사용되는 것이 바로 리스트(list) 타입입니다.
- 리스트는 데이터들을 잘 관리하기 위해서 묶어서 관리할 수 있는 자료형 중의 하나 입니다.
1) 리스트 만들기
- 파이썬에서 리스트는 다음과같은 구조로 만들 수 있습니다
변수이름 = [요소1,요소2]
- 이렇게 대괄호를 이용해서 리스트를 만들 수 있으며, 리스트 내부에 값은 문자열이 오든, 숫자가 오든 데이터 타입이 통일되지 않아도 상관없습니다.
ex)
states_of_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia"]
print(states_of_america)
[결과]: ['Delaware', 'Pencilvania', 'New Jersey', 'Georgia']
2) 리스트에 값 추가하기
- 리스트의 append 함수를 이용해서 리스트의 끝에 값을 추가할 수 있습니다
ex)
states_of_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia"]
states_of_america.append("Texas")
print(states_of_america)
[결과]: ['Delaware', 'Pencilvania', 'New Jersey', 'Georgia', 'Texas']
2-1 리스트에 여러값들을 추가하기
- 리스트에 한가지 값이 아닌 여러가지 값들을 추가하고 싶을때는 extend 함수를 이용해서 추가할 수 있습니다
ex)
states_of_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia"]
states_of_america.extend(["New York", "Ohaio"])
print(states_of_america)
[결과]: states_of_america = ['Delaware', 'Pennsylvania', 'New Jersey', 'Georgia', 'New York', 'Ohaio']
3) 리스트 값 삭제하기
- 리스트의 remove함수를 이용해서 특정 값을 리스트에서 삭제할 수 있습니다
ex)
fruits_vegetables = [
"Strawberries", "Spinach", "Kale", "Nectarines", "Apples", "Grapes",
"Peaches", "Cherries", "Pears", "Tomatoes", "Celery", "Potatoes"
]
fruits_vegetables.remove("Strawberries")
print(fruits_vegetables)
[결과]: ['Spinach', 'Kale', 'Nectarines', 'Apples', 'Grapes', 'Peaches', 'Cherries', 'Pears', 'Tomatoes', 'Celery', 'Potatoes']
4) 실습 예제
Exercise)
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
위 코드를 수정하지 않고 코드를 추가하여 입력된 이름을 랜덤으로 뽑아 밥값을 내는 프로그램을 작성하세요
*Hint* 리스트를 사용하고, len()함수를 사용해 보세요
Solution)
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
import random
len_names = len(names)
rand_name = random.randint(0, len_names - 1)
person = names[rand_name]
print(f"{person} is going to buy the meal today")
- 랜덤 모듈을 불러옵니다
- 입력된 이름이 몇개인지 len()함수로 개수를 셉니다
- 랜덤하게 뽑기 위해 random.randint함수를 사용합니다
- 랜덤으로 뽑힌 값을 리스트에 대입해야 하기 때문에 0부터 시작하여 변수에서 1을 뺀 숫자까지만 뽑게 합니다
- person이라는 변수에 랜덤하게 뽑힌값을 names리스트에 넣어줍니다
- 그렇게 되면 예를 들어 이름이 5개면 0부터 4까지 랜덤하게 값을 뽑고 3이 뽑혔다면 names[3]이 되어 names 리스트의 3자리의 위치한 이름이 출력됩니다
- f스트링으로 person변수를 대입해 밥값낼 사람이 누구인지 출력합니다
2. 중첩 리스트
- 중첩 리스트는 리스트안에 또다른 리스트가 있는것으로 즉, 두개의 리스트를 하나로 합친것입니다.
ex)
list1 = [1,2,3,4,5]
list2 = ["a","b", "c", "d", "e"]
list3 = [list1, list2]
print(list3[1],[1])
- 위 코드의 내용은 list1,list2 두개의 리스트를 list3로 묶어서 list3의 1번 리스트에 1번요소를 출력하란 내용입니다
- 즉 출력문은 b입니다
Exercise)
fruits = ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears"]
vegetables = ["Spinach", "Kale", "Celery", "Potatoes"]
dirty_dozen = [fruits, vegetables]
print(dirty_dozen[0][1])
- fruits와 vegetables라는 두개의 리스트를 만듭니다
- dirty_dozen이라는 리스트로 두개의 리스트를 묶습니다
- dirty_dozen리스트의 0번째 리스트에서 1번째 요소를 출력합니다
1) 실습예제
Exercise)
row1 = ["⬜️", "⬜️", "⬜️"]
row2 = ["⬜️", "⬜️", "⬜️"]
row3 = ["⬜️", "⬜️", "⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
print(f"{row1}\n{row2}\n{row3}")
위 코드를 수정하지 않고 중간에 코드를 추가하여 두자리의 정수를 입력받았을 때 행렬의 위치로 x가 표시되는 프로그램을 작성하세요
ex) 입력값: 23
2행3열의 위치에 X가 표시되면 됩니다.
row1 = ["⬜️", "⬜️", "⬜️"]
row2 = ["⬜️", "⬜️", "X"]
row3 = ["⬜️", "⬜️", "⬜️"]
Solution)
row1 = ["⬜️", "⬜️", "⬜️"]
row2 = ["⬜️", "⬜️", "⬜️"]
row3 = ["⬜️", "⬜️", "⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
first_position = int(position[0])
second_position = int(position[1])
select_map = map[first_position - 1]
select_map[second_position - 1] = "x"
print(f"{row1}\n{row2}\n{row3}")
- 입력받은 두자리 정수를 리스트를 이용해 0번째와 1번째 수로 나눕니다
- 만약 13을 입력했다면 첫번째 수는 1이지만 이를 0번째부터 시작하는 리스트에 대입해야 하기때문에 해당 변수에 -1을 하여 map리스트에 대입합니다
- 따라서 13의 첫번째 자리인 1은 map리스트의 0번째인 row1리스트가 출력됩니다
- 두번째 자리인 3은 아까 선택된 row1리스트에서 2번째 요소이고 그 안에 x를 대입합니다
3. 가위바위보 게임
Exercise)
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
위 코드는 수정하지 않고 코드를 추가하여 컴퓨터와 가위바위보 게임을 하는 프로그램을 만드세요
* 조건은 0은 바위 1은 보 2는 가위로 생각합니다
Solution)
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
list = [rock, paper, scissors]
human = input(
"What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors\n")
int_human = int(human)
human_list = list[int_human]
print(human_list)
print("Computer chose:\n")
import random
rand_computer = random.randint(0, 2)
int_computer = rand_computer
computer_list = list[int_computer]
print(computer_list)
if human_list == computer_list:
print("You Draw")
elif int_human == 0 and int_computer == 1:
print("You Lose")
elif int_human == 0 and int_computer == 2:
print("You Win")
elif int_human == 1 and int_computer == 0:
print("You Win")
elif int_human == 1 and int_computer == 2:
print("You Lose")
elif int_human == 2 and int_computer == 0:
print("You Lose")
elif int_human == 2 and int_computer == 1:
print("You Win")
- 리스트를 만들어 그안에 가위,바위,보를 삽입합니다
- 사용자가 어떤것을 낼지 입력받습니다
- 선택한 숫자를 문자형에서 정수형으로 변환합니다
- 정수형으로 변환한 숫자를 list에 값으로 넣고 human_list 변수에 저장합니다
- 사용자가 선택한 타입을 출력합니다
- 컴퓨터가 낼 타입을 만들기 위해 랜덤모듈을 불러옵니다
- random.randint함수로 0부터 2까지 랜덤하게 뽑게 합니다
- 마찬가지로 뽑은 수를 list에 값으로 넣고 computer_list 변수에 저장합니다
- 컴퓨터가 선택한 타입을 출력합니다
- if문을 이용해 사용자와 컴퓨터가 선택한 숫자가 똑같으면 비겼다고 알려주고, 경우의 수를 하나하나 조건문으로 만들어서 승부의 결과를 출력합니다
Solution2)
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
list = [rock, paper, scissors]
human = input(
"What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors\n")
int_human = int(human)
human_list = list[int_human]
print(human_list)
print("Computer chose:\n")
import random
rand_computer = random.randint(0, 2)
int_computer = rand_computer
computer_list = list[int_computer]
print(computer_list)
if int_human == 0 and int_computer == 2:
print("You Win")
elif int_computer == 0 and int_human == 2:
print("You Lose")
elif int_human < int_computer:
print("You Lose")
elif int_human > int_computer:
print("You Win")
else:
print("You Draw")
- 하지만 위와같은 방식은 코드가 길어지고 코드가 계속 길어질경우 프로그램의 효율성이 떨어집니다
- 이런 문제점을 보완하기 위해 코드를 단축할 수 있으면 최대한 단축하는게 프로그래밍을 잘하는 방법입니다
- 따라서 조건문을 좀 더 간단하게 바꾸어 보겠습니다
- 사람이 0을 선택했을 때와 컴퓨터가 2를 선택했을 때 그리고 반대의 경우는 조건을 상세하게 넣어서 조건문을 만듭니다
- 위 조건들이 거짓일 경우 밑에 elif문으로 사용자가 컴퓨터가 낸 값보다 클경우와 작을 경우의 조건문을 만듭니다
- 그외에 경우는 숫자가 같을 경우이기 때문에 비겼다는 출력문을 출력합니다
'Python Study' 카테고리의 다른 글
Python Study(함수 정의 및 호출/들여쓰기) (0) | 2023.02.18 |
---|---|
Python Study(반복문(for)) (0) | 2023.02.05 |
Python Study(random모듈) (0) | 2023.02.01 |
Python Study(조건문/중첩 조건문/논리 연산자) (0) | 2023.01.26 |
Python Study(데이터 형식/연산자/F-String) (0) | 2023.01.25 |