자료구조
리스트
- 리스트는 다양한 자료형을 한 곳에 묶어두는 역할을 한다.
- [ ]를 통해 묶어서 리스트를 선언할 수 있으며, 서로 다른 자료형을 하나의 리스트에 저장하는 것도 가능하다.
name = ["철수", "영희", "민수"]
score = [90, 96, 40]
name.append("예슬")
score.append(80)
name.insert(3, "동준")
score.insert(3, 75)
name.pop()
print(name.count("영희"))
print("민수 점수 : " + str(score[name.index("민수")]))
num = [5, 3, 4, 2, 1]
num.sort()
num.reverse()
num.clear()
num_2 = [6, 7, 8, 9, 10]
num.extend(num_2)
사전
- 사전(dictionary)은 key와 value로 구성되어 있다.
- 각 value는 각자의 key를 갖고 있으며 key는 중복될 수 없다.
- key를 통해 해당하는 value를 조회할 수 있다.
- value를 통해 key를 조회할 수는 없다.
- {}를 통해 사전을 선언할 수 있으며 ':'를 기준으로 앞은 key, 뒤는 value를 의미한다.
capital = {"대한민국":"서울", "미국":"워싱턴", "일본":"도쿄", "중국":"베이징"}
print(capital)
print(capital["중국"])
print(capital.get("대한민국"))
print(capital.get("부산", "잘못된 key"))
print("영국" in capital)
capital["영국"] = "런던"
capital["일본"] = "동경"
del capital["미국"]
print(capital.keys())
print(capital.values())
print(capital.items())
capital.clear()
튜플
- 튜플은 list와 비슷하지만 내용을 추가하거나 수정할 수 없다.
- 하지만 list보다 속도가 빠르다.
- ()로 튜플 선언이 가능하다.
food = ("짜장면", "짬뽕")
print(food)
print(menu[0])
food.add("탕수육")
food, price, is_spicy = ("짜장면", 6000, False)
print(food)
print(price)
print(is_spicy)
세트
- 세트는 집합을 의미한다.
- 중복이 안되고 순서가 존재하지 않는다.
- {}를 이용하여 세트를 선언할 수 있다.
my_set = {5, 5, 5, 1, 1, 1, 2, 2, 3, 3, 3, 0, 0, 0}
print(my_set)
menu = {"짜장면", "짬뽕", "탕수육"}
favorite = set(["짜장면", "냉면"])
print(menu & favorite)
print(menu.intersection(favorite))
print(menu|favorite)
print(menu.union(favorite))
print(menu - favorite)
print(menu.difference(favorite))
favorite.add("칼국수")
favorite.remove("냉면")
자료 구조의 변경
- 앞서 배운 세트, 리스트, 튜플은 서로 자료 구조 변경이 가능하다.
food = {"짜장면", "짬뽕", "탕수육"}
print(food, type(food))
food = list(food)
print(food, type(food))
food = tuple(food)
print(food, type(food))
food = set(food)
print(food, type(food))
연습문제
- 손님 20명 중 추첨을 통해 1명은 탕수육을, 3명은 짜장면을 준다고 할 때, 당첨자를 뽑아낼 코드를 작성하기.
- 규칙 1 : 아이디는 편의상 1~20으로 설정
- 규칙 2 : 중복 당첨은 불가능
- 규칙 3 : random 모듈의 shuffle과 sample 활용
from random import *
id_list = list(range(1, 21))
shuffle(id_list)
win = sample(id_list, 4)
print(f'''
당첨자 발표
탕수육 당첨자 : {win[0]}
짜장면 당첨자 : {win[1]}, {win[2]}, {win[3]}
''')