3주: day16

daye·2023년 3월 18일

달성한 목표

강의 : 자료구조 3~5
팀플 과제 : 작성한 과제 노션 옮기기 / 팀 스터디 노트

정리할 파트

강의 : 자료구조 3~9

10 리스트에 아이템 추가

append()

: 마지막 위치(인덱스)에 아이템을 추가할 수 있다.
(자동으로 길이도 늘어남)

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

11 리스트의 특정 위치에 아이템 추가

insert()

: 특정 위치(인덱스)에 아이템을 추가할 수 있다.
추가한 후, 원래 있던 아이템들은 뒤로 한칸씩 밀려난다.

  • insert(위치 번호, 넣을 아이템)

12 리스트의 아이템 삭제

pop()

: 마지막 인덱스에 해당하는 아이템을 삭제할 수 있다.

  • pop(n)
    : n 인덱스에 해당하는 아이템을 삭제할 수 있다.
    (나머지 아이템들은 한 칸씩 앞으로)
  • pop()로 삭제한 값을 알고 싶을 때:
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
이

13 리스트의 특정 아이템 삭제 **실습

remove()

: 특정 아이템을 삭제할 수 있다.

  • remove()는 한 개의 아이템만 삭제 가능하다.
students = ['홍', '박', '이', '최', '김', '강', '박']
students.remove('박')
print(students)

# 결과
['홍', '이', '최', '김', '강', '박']		# 하나의 '박'만 제거됨
students = ['홍', '박', '이', '최', '김', '강', '박']

while '박' in students:
	students.remove('박')
    
print(students)

# 결과
['홍', '이', '최', '김', '강']				# 두 '박' 모두 제거됨

14 리스트 연결

extend()

: 리스트에 또다른 리스트를 연결(확장)할 수 있다.

  • 리스트A에 extend()를 이용해 리스트B를 연결하면, 리스트A가 확장되는 것.
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']

+ (덧셈 연산자)

  • 리스트A와 리스트C를 덧셈 연산자를 이용해 연결하면, 내용은 그대로지만 리스트C라는 새 리스트가 만들어진다.
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']

15 리스트 아이템 정렬

sort()

: 오름차순 정렬

  • sort(reverse=True)
    : 내림차순
  • 숫자, 문자열 모두 정렬 가능

16 리스트 아이템 순서 뒤집기

reverse()

  • 정렬과는 관계 없음
  • 아이템들의 순서를 정반대로 바꾸는 것
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]

17 리스트 슬라이싱

: 리스트에서 내가 원하는 부분만 뽑아내는 것

[n:m]

: 인덱스 n부터 인덱스 m앞까지의 아이템을 가져온다.

  • [:m] : 맨 앞부터 m앞까지
  • [n:] : n부터 맨뒤까지
  • 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', '김', '강']

slice()

students = ['홍', '박', '이', '최', '김', '강']
print(students[slice(2, 4)])
print(students[slice(4)])
print(students[slice(2, len(students))])
print(students[slice(2, len(students)-2)])

# 결과
['이', '최']
['홍', '박', '이', '최']
['이', '최', '김', '강']
['이', '최']

18 리스트의 나머지 기능들

  • 리스트를 곱셈 연산하면 아이템이 반복된다

index()

: 아이템의 인덱스를 알아낼 수 있다.

  • index로 어떤 아이템을 찾을 때, 가장 앞쪽에 나오는 것만 찾는다.(아래)
students = ['홍', '강', '박', '이', '최', '김', '강']

searchIdx = students.index('강')				#'강'이 2개인데 맨 앞쪽 것만 찾음
print('searchIdx: {}'.format(searchIdx))

searchIdx = students.index('강', 2, 6)		# 범위 지정
print('searchIdx: {}'.format(searchIdx))

# 결과
searchIdx: 1
searchIdx: 5

random.sample(range(a, b), c)

: a부터 b-1까지의 수 중 랜덤으로 c개를 발생시킨다 (import random)

  • 항상 리스트 타입으로 반환해준다.

19

count()

: 특정 아이템의 개수를 알아낼 수 있다.

searchCnt = students.count('강')

del

: 특정 아이템을 삭제할 수 있다.

del students[1]
print(students)

del students[1:4]
print(students)

del students[2:]
print(students)

# 결과
['홍', '박', '이', '최', '김', '강']
['홍', '김', '강']
['홍', '김']

20 튜플 (Tuple)

: 리스트와 비슷하지만, 아이템 변경이 불가능하다.

  • ()를 이용해 선언, 데이터의 구분은 , 이용
  • 튜플에 속한 데이터 하나하나를 '엘리먼트' 또는 '아이템' 또는 '요소' 라고 함
  • 숫자, 문자, 논리형 등 모든 기본 데이터를 같이 저장할 수 있다.
  • 튜플 안에 또다른 컨테이너 자료형 데이터를 저장할 수도 있다.
  • 데이터 타입 : tuple

21 튜플 아이템 조회

  • 리스트와 마찬가지로 아이템에 자동으로 부여되는 번호표(인덱스)가 있다.
  • 튜플 아이템은 인덱스를 이용해 조회가 가능하다.
students = ('홍', '강', '박', '이', '최', '김')
print('students[2]: {}'.format(students[2]))

# 결과
students[2]: 박

22 in 과 not in 키워드

: 아이템의 존재 유/무를 알 수 있다.

  • in이면(아이템이 있으면) True, 아니면(없으면) False
  • not in 은 반대
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))

23 튜플 길이

: 튜플에 저장된 아이템 개수

for i in range(len(students))
	print('i : {}'.format(i))
    print('students[{}] : {}'.format(i, students[i]))
for s in students:
	print('student: {}'.format(s))

24 튜플 결합

  • 두 개의 튜플을 결합할 수 있다. (결과로 새로운 튜플이 만들어진다.)

리스트 vs 튜플

  • 리스트에서 사용할 수 있는 extend()함수를 튜플에서는 사용할 수 없다.
    (튜퓰은 한 번 선언되면 데이터의 수정이 불가능하기 때문에)
myNum = (1, 2, 3, 4, 5)
friendNum = (4, 5, 6, 7, 8)

for number in friendNum:
	if number not in myNum:
    	myNum = myNum + (number, )

25 튜플 슬라이싱

  • [n:m] 을 이용해 원하는 아이템만 뽑아낼 수 있다.
  • 슬라이싱할 때 단계를 설정할 수 있다.
    **
  • 튜플은 슬라이싱을 이용해서 아이템을 변경할 수 없다.
  • 리스트에 튜플 아이템으로 변경 가능

slice()

26 리스트와 튜플

  • 튜플은 리스트와 달리 아이템 추가, 변경 삭제가 불가하다.
  • 튜플은 선언 시 괄호 생략이 가능하다
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'>

27 튜플 아이템 정렬

  • 튜플은 수정이 불가하기 때문에 리스트로 변환 후 정렬한다.
  • list() -> sort() or sort(reverse=True) -> tuple()
students.sort()

sorted()

  • sorted() 함수를 이용하면 튜플도 정렬할 수 있다.
  • sorted()는 리스트 자료형을 반환한다. (원본 데이터는 tuple 그대로 유지)
  • sorted()는 sort()처럼 자료구조에 포함되어 있는 함수가 아니라 내장함수.
students = ('홍', '강', '박', '이', '최', '김')

sortedStudents = sorted(students)	# 내장함수
print('sortedStudents type : {}'.format(type(sortedStudents)))
print('sortedStudents : {}'.format(sortedStudents))

# 결과
sortedStudents type : <class 'list'>
sortedStudents : ['강', '김', '박', '이', '최', '홍']

28 튜플과 for문

  • for문을 이용하면 튜플의 아이템을 자동으로 참조할 수 있다.
students = '홍', '강', '박', '이', '최', '김'

for i in range(len(students)):
	print(cars[i])
    
for student in students:
	print(student)
# students 자리에는 반복이 되는(리터러블한) 객체가 올 수 있다.

# 결과
홍
강
박
이
최
김
  • for문을 이용하면 튜플의 아이템을 자동으로 참조할 수 있다.
  • for문을 이용하면 튜플 내부에 또 다르 튜플의 아이템을 조회할 수도 있다.
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

29

  • for문과 if문

30 튜플과 while문

31

32 딕셔너리(Dictionary)

: 키(key)와 값(value)을 이용해서 자료를 관리한다.

  • 리스트와 튜플은 데이터를 줄세우는 것이고, '자동으로' 번호표(인덱스)가 붙는다.
  • 반면, 딕셔너리는 인덱스가 존재하지 않는다. 대신 키(key)가 그 역할을 하는데, 키 값은 내가 부여해야한다.
  • 리스트나 튜플은 아이템이 중복되어도 되지만, 딕셔너리의 키는 중복되면 안되고 아이템은 중복 값이 있어도 된다.
memInfo = {'이름':'홍길동', '메일':'abc@gamil.com', '학년':3, '취미':['농구', '게임']}
studentInfo - {1:student1, 2:student2, 3:student3}
  • {}를 이용해 선언, '키:값'의 형태로 이 한쌍이 아이템(요소)이다.
  • key와 value에는 숫자, 문자, 논리형 뿐 아니라 컨테이너 자료형도 올 수 있다.
  • 단, key에 immutable(변경이 불가능한) 값(ex/ 튜플)은 올 수 있지만 mutable 값(ex/ 리스트)은 올 수 없다.

33 딕셔너리 조회

  • 딕셔너리는 key를 이용해서 값(value)을 조회한다.
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()

: get(key)를 이용해서 값(value)을 조회할 수 있다.

print(students.get('s1'))
print(students.get('9999'))		# 존재하지 않는 key를 불렀을 때

print(students['s9'])

# 결과
홍
None
(에러메시지가 뜬다)

34 딕셔너리 추가

  • 딕셔너리이름[키(key)] = 값(value)
  • 추가하려는 키가 이미 있다면, 기존 값이 변경된다.
myInfo = {}

myInfo['이름'] = '박경진'
myInfo['전공'] = '컴퓨터'
print(myInfo)

myInfo['전공'] = '통계'
print(myInfo)

# 결과
{'이름':'박경진', '전공':'컴퓨터'}
{'이름':'박경진', '전공':'통계'}

35 딕셔너리 수정

  • 딕셔너리이름[키(key)] = 값(value)

36 key()와 values()

: 전체 키(key)와 값(value)을 조회할 수 있다.

  • dict 안에 list가 저장된 형태로

itmes()

: 키:값 을 모두 조회할 수 있다.

  • dict 안에 list 안에 tuple이 저장된 형태로
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'>
  • list로 변환하기
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문을 이용한 조회
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]}')
    
# 결과
이름: 박경진
전공: 컴퓨터

37 딕셔너리 삭제

del

: del과 key를 이용한 item 삭제

del memInfo['전공']
print(f'memInfo: {memInfo}')

# 결과
memInfo: {'이름': '박경진'}

pop()

: pop()과 key를 이용한 item 삭제

  • del과 달리 삭제된 값을 반환할 수 있다.
returnValue = memInfo.pop('이름')
print(f'memInfo: {memInfo}')
print(f'returnValue: {returnValue}')
print(f'returnValue type: {type(returnValue)}')

# 결과
memInfo: {'전공': '컴퓨터'}
returnValue: 박경진
returnValue type: <class 'str'>

38 딕셔너리 유용한 기능

in, not in

  • 키(key) 존재 유/무를 판단한다.
print('이름' in memInfo)
print('학년' in memInfo)

# 결과
True
False

len()

: 딕셔너리 길이(아이템 개수)를 알 수 있다.

print(len(memInfo))

# 결과
2

clear()

: 모든 아이템을 삭제한다.

memInfo.clear()
print(memInfo)

# 결과
{}

0개의 댓글