리스트
- 파이썬에서 가장 많이 사용하는 유형
- 여러 개의 변수를 하나로 묶는 container type
- 대괄호([ ])를 이용해서 만들며, 다양한 자료형을 담을 수 있음.
변수 할당
nums = [1, 2, 3, 4, 5] cars = ['taxi', 'bus', 'truck'] money = ['1000원', '1dollar', '20엔', 10000, nums, line] print(nums) print(cars) print(money)인덱싱
money = ['1000원', '1dollar', '20엔', 10000] print(money[0]) print(money[1]) print(money[-1])슬라이싱
money = ['1000원', '1dollar', '20엔', 10000] print(money[:1]) print(money[1:]) print(money[1:3]) #3은 포함하지 않음 print(type(money[1])) print(type(money[0]))이중 리스트
won = [1000, 2000, 3000, 4000] dollar = [1, 2, 3, 4] money = [won, dollar] print(won) print(type(won)) print(money) print(type(money)) print(type(money[0])) print(money[:1]) print(type(money[:1]))원소 변경
cheeses = ['체다', '모짜렐라', '리코타'] print(cheeses) cheeses[0] = '까망베르' print(cheeses)리스트 더하기
cheeses = ['체다', '모짜렐라', '리코타'] cheese = ['까망베르'] print(cheeses) print(cheese) new_cheeses = cheeses + cheese print(new_cheeses)
메서드
index
리스트 요소의 index를 찾아주는 메서드
cheeses = ['체다', '모짜렐라', '리코타', '까망베르'] print(cheeses.index('체다')) # 없는 value값을 넣을 경우 오류 발생
0
append
리스트 끝 부분에 새로운 요소를 추가하는 메서드
cheeses = ['체다', '모짜렐라', '리코타', '까망베르'] cheeses.append('고르곤') print(cheeses) cheeses.append('아메리칸') print(cheeses)insert
리스트에서 원하는 index에 요소를 끼워 넣는 메서드
cheeses = ['체다', '모짜렐라', '리코타', '까망베르'] cheeses.insert(1, '고르곤') print(cheeses)extend
- 본 리스트에 둘 이상의 요소로 구성된 리스트를 연장시키는 메서드
- 두 리스트를 더하는 효과(+)와 동일
cheeses = ['체다', '모짜렐라', '리코타', '까망베르'] cheeses.extend(['피자', '핫도그']) print(cheeses)sort(정렬)
nums = [200, 500, 100, 1000] print(nums) nums.sort() print(nums)주의
기존의 데이터에서 정렬하기 때문에
할당으로 하고 정렬을 할 경우 오류print(nums) line() new_nums = nums.sort() print(new_nums)sorted
원본을 변경하지 않고 정렬하기
nums = [200, 500, 100, 1000] sorted_nums = sorted(nums) print(sorted_nums) print(nums)내림차순
sorted(nums, reverse=True)pop
리스트의 마지막 요소를 return으로 넘겨주고, 원본 리스트에서는 제거하는 메서드
nums = [200, 500, 100, 1000] return_val = nums.pop() print(return_val) print(nums)pop(index)
인덱스를 인자로 넣어주고, 해당 인덱스 위치의 value를 return할 수 있음.
nums = [200, 500, 100, 1000] return_val = nums.pop(1) print(return_val) print(nums)remove
- 메서드의 인자로 리스트의 요소를 넣어주면, 해당요소가 제거됨.
- index 정보로 요소를 제거할 때는 pop, 요소 정보로 제거할 때는 remove를 사용
- 원본 변경에 주의
nums = [200, 500, 100, 1000] nums.remove(500) print(nums)count
메서드의 인자로 리스트의 요소로 넣어주고, 해당 요소가 리스트에서 몇 번 등장하는지 알려주는 메서드
nums = [200, 500, 100, 1000, 500] print(nums.count(500내장함수와 리스트
리스트와 궁합이 잘 맞는 파이썬 내장 함수
nums = [200, 500, 100, 1000, 500] print(nums) line() print(len(nums)) line() print(max(nums)) line() print(min(nums)) line() print(sum(nums)) line() print(sorted(nums))
#문제1 a = [100, 200 ,300 ,400 ,500] a[0] = 2000 print(a)
#문제2 fruit = ['banana', 'apple', 'mango', 'melon'] del fruit[3] print(fruit)
#문제3 lang = ['c' , 'c++', 'c#'] lang.append('java') print(lang)
#문제4 nums = [20, 400, 100, 60, 10] print(sorted(nums))
#문제5 score = [85, 92, 78, 90, 88] print(score.index(90))
튜플
- 리스트와 매우 비슷함.
- 읽기 전용이어서 변경이 불가하다는 점이 리스트와 다름.
- 리스트보다 속도가 빠르고, 데이터 전달에 안전
딕셔너리
- '사전'이란 의미인데, key(색인)와 value(값) 세트로 된 구조
- 마치 사전에 수록된 모양으로 된 데이터 형식과 비슷함.
- 낱말과 뜻풀이 형태로 된 형식
- 딕셔너리에서는 이를 각각 키(key)와 값(value)이라고 부른다.
변수 할당1 : base
dic = {'name':'serendipi27', 'age': 1000, 'color':'red'} print(dic) print(type(dic)변수 할당2 : dict
- dict() 함수 이용 + tuple(원소 두 개로 이루어진 리스트 또는 tuple)
- 이중리스트나 이중 튜플 모두 다 되고, 내부 리스트에는 2개의 요소가 들어가 있으면 됨.
tup = ((1, '서울'), (2, '대전'), (3, '대구'), (4, '부산')) dic = dict(tup) print(dic)변수 할당3
- 리스트 컴프레헨션을 위한 dict 변수 할당
- 외부 리스트든, 외부 튜플이든 모두 동일한 결과
dic1 = dict((i, i**2) for i in range(5)) # 튜플은 양 괄호(())를 생략 가능하기 때문에 이 코드는 True임. dic2 = dict([(i, i**2) for i in range(5)]) print(dic1) print(type(dic1)) print(dic2) print(type(dic2))
dict의 key를 이용한 value 찾기
tup = ((1, '서울'), (2, '대전'), (3, '대구'), (4, '부산')) dic = dict(tup) print(dic[1]) # dictonary의 메소드 # 동일하게 작동하나, 찾고자하는 값이 없을 경우 에러가 아닌 None 출력 print(dic.get(1)) print(dic[4]) print(dic.get(4))dict의 value 수정하기
print(dic) dic[1] = '일산' print(dic)dict의 새로운 value 추가하기
- DataFrame에서 새로운 열을 만들고 Series를 추가하는 것과 비슷함.
- key-value의 dict base
print(dic) dic[10] = '하동' print(dic)
메서드
- items(), keys(), values()
- 실제 사용을 하려면, 이 메서드 적용 후, list(), tuple()로 wrapptin 해줘야함
- 또는 iterator로 활용
print(dic) line() print(dic.keys()) line() print(dic.values()) line() print(dic.items()) line()
딕셔너리의 모든 키 출력
for key, value in dic.items(): print(f'{key}:{value}')
연습문제
# 문제1 data = {"name": "Alice", "age": 30, "city": "New York"} print(data['name']) line()
# 문제2 data = {"name": "Bob", "age": 25, "country": "Canada"} data['hometown'] = 'soul' print(data) line()
# 문제3 data = {"name": "Carol", "age": 35, "city": "London"} for key in data.items(): print(f'{key}')
셋
- 수학에 나오는 집합(set) 연산을 처리하기 위한 자료형
- 중복을 허용하지 않음
- 순서를 고려하지 않음
- 순서를 고려해 처리해야 한다면 리스트나 튜플 자료형으로 변환이 필요함.
변수 입력하기
name = input('이름을 입력하여 주세요') age = int(input('나이를 입력하여 주세요.')) print(name) print(type(name)) print(age) print(type(age))