[Python][자료구조] 튜플 : 아이템 조회, 결합

·2023년 3월 20일
0
post-thumbnail

✒️ 튜플이란?

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

  • 리스트 : 아이템 변경(수정, 삭제) 가능
  • 아이템 변경 불가능

'()'을 이용해서 선언하고, 데이터 구분은 ','를 이용한다

students = ('짱구', '철수', '유리', '훈이', '맹구')
print(f'students = {students}')
print(f'students = {type(students)}')
💡result
students = ('짱구', '철수', '유리', '훈이', '맹구')
students = <class 'tuple'>

✒️아이템 조회

인덱스 : 튜플도 리스트와 마찬가지로 아이템에 자동으로 부여되는 번호표가 있다.

students = ('짱구', '철수', '유리', '훈이', '맹구')
for i in range(len(students)):
    print(f'student[{i}] = {students[i]}')
💡result
 
student[0] = 짱구
student[1] = 철수
student[2] = 유리
student[3] = 훈이
student[4] = 맹구

✍️실습

5명의 학생 이름을 튜플에 저장하고 인덱스가 홀수인 학생과 짝수인 학생 구분

students = ('짱구', '철수', '유리', '훈이', '맹구')
for i in range(len(students)):
    if i % 2 == 0:
        print(f'짝 : student[{i}] = {students[i]}')
    else:
        print(f'홀 : student[{i}] = {students[i]}')
💡result

짝 : student[0] = 짱구
홀 : student[1] = 철수
짝 : student[2] = 유리
홀 : student[3] = 훈이
짝 : student[4] = 맹구

📌in 과 not in

students = ('짱구', '철수', '유리', '훈이', '맹구')
inputName = input('학생 이름 : ')
if inputName not in students:
    print(f'{inputName}은 존재하지 않는 학생입니다.')
else:
    print(f'{inputName}은 존재하는 학생입니다.')
💡result

학생 이름 : 서태웅
서태웅은 존재하지 않는 학생입니다

✍️실습

문장에 비속어가 있는지 알아내는 프로그램


# 비속어 판단 프로그램
wrongWord = ('존나', '미친', '쪼갬', '닥쳐', '빡침')
sentence = '오늘 날씨 존나 좋아. ' \
           '근데 버스 눈 앞에서 놓쳐서 개빡침.' \
           ' 그래서 친구가 옆에서 개쪼갬'

for wrong in wrongWord:
    if wrong in sentence:
        print(f'비속어 : [{wrong}] 사용❗')
💡result

비속어 : [존나] 사용❗
비속어 : [쪼갬] 사용❗
비속어 : [빡침] 사용❗

📌 len() 함수와 반복문을 이용한 조회

# 튜플 길이
students = ('짱구', '철수', '유리', '훈이', '맹구')
print(f'students 길이 : {len(students)}')

n = 0
while n < len(students):
    print(f'student[{n}] : {students[n]}')
    n += 1
    
💡result

students 길이 : 5
student[0] : 짱구
student[1] : 철수
student[2] : 유리
student[3] : 훈이
student[4] : 맹구

✒️튜플 결합

두 개의 튜플을 결합할 수 있다 .

# 튜플 결합
students1 = ('짱구', '철수', '유리')
students2 = ('훈이', '맹구')
print(students1)
print(students2)
print(students1 + students2)
💡result

('짱구', '철수', '유리')
('훈이', '맹구')
('짱구', '철수', '유리', '훈이', '맹구')

리스트에서 사용할 수 있는 extend() 함수는 사용할 수 없다.

# extend()
print(students1.extend(students2))
💡result
AttributeError: 'tuple' object has no attribute 'extend'

✍️실습

나와 친구가 좋아하는 번호를 합치되 번호가 중복되지 않게 하는 프로그램

📌데이터를 tuple타입으로 변경 방법 = (데이터, )

myFavorite = (3, 8, 12, 4, 1, 6)
friendFavorite = (1, 2, 3, 4, 5, 6)

for friend in friendFavorite:
    if friend not in myFavorite:
        myFavorite = myFavorite + (friend,) #int타입을 tuple로 변경  

print(f'myFavorite : {myFavorite}')
💡result
myFavorite : (3, 8, 12, 4, 1, 6, 2, 5)

✒️ 튜플 슬라이싱

리스트와 마찬가지로 [n:m]을 이용하면 리스트에서 원하는 아이템을 뽑아낼 수 있다.


students = ('짱구', '철수', '유리', '훈이', '맹구')
print(f'students[2:] : {students[2:]}')
print(f'students[1:4] : {students[1:5]}')
print(f'students[:10] : {students[:10]}')
print(f'students[-1:2] : {students[-1:2]}')
print(f'students[-4:2] : {students[-4:2]}')
print(f'students[-4:1] : {students[-4:1]}')
print(f'students[-4:5] : {students[-4:5]}')
print(f'students[-4:] : {students[-4:]}')
print(f'students[1:-2] : {students[1:-2]}')
💡result
students[1:4] : ('철수', '유리', '훈이', '맹구')
students[:10] : ('짱구', '철수', '유리', '훈이', '맹구')
students[-1:2] : ()
students[-4:2] : ('철수',)
students[-4:1] : ()
students[-4:5] : ('철수', '유리', '훈이', '맹구')
students[-4:] : ('철수', '유리', '훈이', '맹구')
students[1:-2] : ('철수', '유리')

단계 설정 가능

print(f'students[2::2] : {students[2::2]}')
students[2::2] : ('유리', '맹구')
profile
개발하고싶은사람

0개의 댓글