강의 : 자료구조 3~5
팀플 과제 : 작성한 과제 노션 옮기기 / 팀 스터디 노트
강의 : 자료구조 3~9
: 마지막 위치(인덱스)에 아이템을 추가할 수 있다.
(자동으로 길이도 늘어남)
scores = [['국어', 88], ['영어', 91]]
print('scores : {}'.format(scores))
print('scores length : {}'.format(len(scores)))
print('last index : {}'.format(len(scores) - 1))
scores.append(['수학', 96])
print('scores length : {}'.format(len(scores)))
# 결과
scores : [['국어', 88], ['영어', 91]]
scores length : 2
last index : 1
scores : [['국어', 88], ['영어', 91], ['수학', 96]]
scores length : 3
: 특정 위치(인덱스)에 아이템을 추가할 수 있다.
추가한 후, 원래 있던 아이템들은 뒤로 한칸씩 밀려난다.
: 마지막 인덱스에 해당하는 아이템을 삭제할 수 있다.
students = ['홍', '박', '이', '최', '김', '강']
print(students)
print('students length : {}'.format(len(students)))
rValue1 = students.pop() # 삭제한 데이터 rValue1에 반환
print(students)
print('students length : {}'.format(len(students)))
print(rValue1) # 삭제한 값을 알고 싶을 때
rValue2 = students.pop(2)
print(students)
print(rValue2) # 삭제한 값을 알고 싶을 때
# 결과
['홍', '박', '이', '최', '김', '강']
6
['홍', '박', '이', '최', '김']
5
강
['홍', '박', '최', '김']
4
이
: 특정 아이템을 삭제할 수 있다.
students = ['홍', '박', '이', '최', '김', '강', '박']
students.remove('박')
print(students)
# 결과
['홍', '이', '최', '김', '강', '박'] # 하나의 '박'만 제거됨
students = ['홍', '박', '이', '최', '김', '강', '박']
while '박' in students:
students.remove('박')
print(students)
# 결과
['홍', '이', '최', '김', '강'] # 두 '박' 모두 제거됨
: 리스트에 또다른 리스트를 연결(확장)할 수 있다.
group1 = ['a', 'b', 'c']
group2 = ['d', 'e', 'f']
print(group1)
print(group2)
group1.extend(group2)
print(group1)
print(group2)
# 결과
['a', 'b', 'c']
['d', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f']
['d', 'e', 'f']
group1 = ['a', 'b', 'c']
group2 = ['d', 'e', 'f']
result = group1 + group2
print(result)
print(group1)
print(group2)
# 결과
['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c']
['d', 'e', 'f']
: 오름차순 정렬
secret = '27156231'
secretList = []
for cha in secret:
secretList.append(int(cha))
print('secretList: {}'.format(secretList))
secretList.reverse()
print('secretList: {}'.format(secretList))
# 결과
secretList: [2, 7, 1, 5, 6, 2, 3, 1]
secretList: [1, 3, 2, 6, 5, 1, 7, 2]
: 리스트에서 내가 원하는 부분만 뽑아내는 것
: 인덱스 n부터 인덱스 m앞까지의 아이템을 가져온다.
students = ['홍', '박', '이', '최', '김', '강']
print(students)
print(students[2:4])
print(students[2:-2])
print(students[-5:-2])
# 결과
['홍', '박', '이', '최', '김', '강']
['이', '최']
['이', '최']
['박', '이', '최']
numbers = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(numbers[2:-2])
print(numbers[2:-2:2])
print(numbers[:-2:2])
print(numbers[::2])
# 결과
[8, 7, 6, 5, 4, 3]
[8, 6, 4]
[10, 8, 6, 4]
[10, 8, 6, 4, 2]
students = ['홍', '박', '이', '최', '김', '강']
print(students)
student[1:4] = ['park', 'lee', 'choi']
print(students)
# 설정 범위 수보다 바꿀 아이템 수가 적으면,
남은 하나가 대체되지 않고 남아 있는 것이 아니라 사라진다.
('park'과 'lee'만 주어졌을 경우, '최'는 students에 남지 않고 사라진다.)
# 결과
['홍', '박', '이', '최', '김', '강']
['홍', 'park', 'lee', 'choi', '김', '강']
students = ['홍', '박', '이', '최', '김', '강']
print(students[slice(2, 4)])
print(students[slice(4)])
print(students[slice(2, len(students))])
print(students[slice(2, len(students)-2)])
# 결과
['이', '최']
['홍', '박', '이', '최']
['이', '최', '김', '강']
['이', '최']
: 아이템의 인덱스를 알아낼 수 있다.
students = ['홍', '강', '박', '이', '최', '김', '강']
searchIdx = students.index('강') #'강'이 2개인데 맨 앞쪽 것만 찾음
print('searchIdx: {}'.format(searchIdx))
searchIdx = students.index('강', 2, 6) # 범위 지정
print('searchIdx: {}'.format(searchIdx))
# 결과
searchIdx: 1
searchIdx: 5
: a부터 b-1까지의 수 중 랜덤으로 c개를 발생시킨다 (import random)
: 특정 아이템의 개수를 알아낼 수 있다.
searchCnt = students.count('강')
: 특정 아이템을 삭제할 수 있다.
del students[1]
print(students)
del students[1:4]
print(students)
del students[2:]
print(students)
# 결과
['홍', '박', '이', '최', '김', '강']
['홍', '김', '강']
['홍', '김']
: 리스트와 비슷하지만, 아이템 변경이 불가능하다.
students = ('홍', '강', '박', '이', '최', '김')
print('students[2]: {}'.format(students[2]))
# 결과
students[2]: 박
: 아이템의 존재 유/무를 알 수 있다.
studentsTuple = ('홍', '강', '박', '이', '최', '김')
searchName = input('학생 성씨 입력: ')
if searchName in studentsTuple: # 이 부분
print('{}는 우리반 학생이다.'.format(searchName))
else:
print('{}는 우리반 학생이 아니다.'.format(searchName))
pythonStr = '아주아주아주 기다란 문장, 문단 혹은 매우 긴 글~~'
print('{} : {}'.format('Python', 'Python' in pythonStr))
# Python이 있으면 True, 없으면 False
wrodWord = ['비', '속', '어', '들']
sentence = '긴 글~~'
for word in wrongWord:
if word in sentence:
print('비속어 : {}'.format(word))
: 튜플에 저장된 아이템 개수
for i in range(len(students))
print('i : {}'.format(i))
print('students[{}] : {}'.format(i, students[i]))
for s in students:
print('student: {}'.format(s))
myNum = (1, 2, 3, 4, 5)
friendNum = (4, 5, 6, 7, 8)
for number in friendNum:
if number not in myNum:
myNum = myNum + (number, )
students = ['홍', '강', '박', '이', '최', '김']
print(type(students))
studentsTuple = ('홍', '강', '박', '이', '최', '김')
print(type(studentsTuple))
studentsTuple = '홍', '강', '박', '이', '최', '김'
print(type(studentsTuple))
# 결과
<class 'list'>
<class 'tuple'>
<class 'tuple'>
students = ['홍', '강', '박', '이', '최', '김']
print(type(students))
students = tuple(students)
print(type(students))
students = list(students)
print(type(students))
# 결과
<class 'list'>
<class 'tuple'>
<class 'list'>
students.sort()
students = ('홍', '강', '박', '이', '최', '김')
sortedStudents = sorted(students) # 내장함수
print('sortedStudents type : {}'.format(type(sortedStudents)))
print('sortedStudents : {}'.format(sortedStudents))
# 결과
sortedStudents type : <class 'list'>
sortedStudents : ['강', '김', '박', '이', '최', '홍']
students = '홍', '강', '박', '이', '최', '김'
for i in range(len(students)):
print(cars[i])
for student in students:
print(student)
# students 자리에는 반복이 되는(리터러블한) 객체가 올 수 있다.
# 결과
홍
강
박
이
최
김
studentCnts = (1, 19), (2, 20), (3, 22), (4, 18), (5, 21)
for classNo, cnt in studentCnts:
print('{}학급 학생 수: {}'.format(classNo, cnt))
for i in range(len(studentCnts)):
print('{}학급 학생 수: {}'.format(studentCnts[i][0], studentCnts[i][1]))
# 동일 결과
1학급 학생 수: 19
2학급 학생 수: 20
3학급 학생 수: 22
4학급 학생 수: 18
5학급 학생 수: 21
: 키(key)와 값(value)을 이용해서 자료를 관리한다.
memInfo = {'이름':'홍길동', '메일':'abc@gamil.com', '학년':3, '취미':['농구', '게임']}
studentInfo - {1:student1, 2:student2, 3:student3}
students = {'s1':'홍', 's2':'강', 's3':'박', 's4':'이', 's5':['최', 'choi']}
print(students['s1'])
print(students['s2'])
print(students['s3'])
print(students['s4'])
print(students['s5'])
print(students['s5'][0])
# 결과
홍
강
박
이
['최', 'choi']
최
: get(key)를 이용해서 값(value)을 조회할 수 있다.
print(students.get('s1'))
print(students.get('9999')) # 존재하지 않는 key를 불렀을 때
print(students['s9'])
# 결과
홍
None
(에러메시지가 뜬다)
myInfo = {}
myInfo['이름'] = '박경진'
myInfo['전공'] = '컴퓨터'
print(myInfo)
myInfo['전공'] = '통계'
print(myInfo)
# 결과
{'이름':'박경진', '전공':'컴퓨터'}
{'이름':'박경진', '전공':'통계'}
: 전체 키(key)와 값(value)을 조회할 수 있다.
: 키:값 을 모두 조회할 수 있다.
memInfo = {'이름':'박경진', '전공':'컴퓨터'}
ks = memInfo.keys()
print(ks)
print(type(ks))
vs = memInfo.values()
print(vs)
print(type(vs))
items = memInfo.items()
print(items)
print(type(items))
# 결과
dict_keys(['이름', '전공'])
<class 'dict_keys'>
dict_keys(['박경진', '컴퓨터'])
<class 'dict_values'>
dict_keys([('이름', '박경진'), ('전공', '컴퓨터')])
<class 'dict_items'>
ks = list(ks)
print(ks)
print(type(ks))
vs = list(vs)
print(vs)
print(type(vs))
items = list(items)
print(items)
print(type(items))
# 결과
['이름', '전공']
<class 'list'>
['박경진', '컴퓨터']
<class 'list'>
[('이름', '박경진'), ('전공', '컴퓨터')]
<class 'list'>
for key in ks:
print(f'key: {key}')
for idx, key in enumerate(ks):
print(f'idx, key: {idx}, {key}')
for item in items:
print(f'item: {item}')
for idx, item in enumerate(items):
print(f'idx, item: {idx}, {item}')
# 결과
key: 이름
key: 전공
idx, key: 0, 이름
idx, key: 1, 전공
item: ('이름', '박경진')
item: ('전공', '컴퓨터')
idx, item: 0, ('이름', '박경진')
idx, item: 1, ('전공', '컴퓨터')
for key in memInfo.keys(): # dict_keys -> 반복성이 있다.
print(f'{key}: {memInfo[key]}')
# 결과
이름: 박경진
전공: 컴퓨터
: del과 key를 이용한 item 삭제
del memInfo['전공']
print(f'memInfo: {memInfo}')
# 결과
memInfo: {'이름': '박경진'}
: pop()과 key를 이용한 item 삭제
returnValue = memInfo.pop('이름')
print(f'memInfo: {memInfo}')
print(f'returnValue: {returnValue}')
print(f'returnValue type: {type(returnValue)}')
# 결과
memInfo: {'전공': '컴퓨터'}
returnValue: 박경진
returnValue type: <class 'str'>
print('이름' in memInfo)
print('학년' in memInfo)
# 결과
True
False
: 딕셔너리 길이(아이템 개수)를 알 수 있다.
print(len(memInfo))
# 결과
2
: 모든 아이템을 삭제한다.
memInfo.clear()
print(memInfo)
# 결과
{}