RUBY
튜플 결합(파이썬) 본문
튜플 결합
두 개의 튜플을 결합할 수 있다.
studentTuple1 = ('홍길동', '박찬호', '이용규')
studentTuple2 = ('박승철', '김지은', '강호동')
studentTuple3 = studentTuple1 + studentTuple2
print('studentTuple3: {}'.format(studentTuple3))
studentTuple3: ('홍길동', '박찬호', '이용규', '박승철', '김지은', '강호동')
리스트에서 사용할 수 있는 extend()함수를 튜플에서는 사용할 수 없다.
studentTuple1 = ['홍길동', '박찬호', '이용규']
studentTuple2 = ['박승철', '김지은', '강호동']
studentTuple1.extend(studentTuple2)
print('studentTuple1: {}'.format(studentTuple1))
→ 정상 출력
studentTuple1 = ('홍길동', '박찬호', '이용규')
studentTuple2 = ('박승철', '김지은', '강호동')
studentTuple1.extend(studentTuple2)
print('studentTuple1: {}'.format(studentTuple1))
→ AttributeError: 'tuple' object has no attribute 'extend'
튜플을 이용해서 나와 친구가 좋아는 번호를 합치되 번호가 중복되지 않게 하는 프로그램을 만들자
myFavoriteNumbers = (1, 3, 5, 6, 7)
friendFavoriteNumbers = (2, 3, 5, 8, 10)
print('내가 좋아하는 번호: {}'.format(myFavoriteNumbers))
print('친구가 좋아하는 번호: {}'.format(friendFavoriteNumbers))
for number in friendFavoriteNumbers:
if number not in myFavoriteNumbers:
myFavoriteNumbers = myFavoriteNumbers + (number, )
print('나와 친구가 좋아하는 번호: {}'.format(myFavoriteNumbers))
내가 좋아하는 번호: (1, 3, 5, 6, 7)
친구가 좋아하는 번호: (2, 3, 5, 8, 10)
나와 친구가 좋아하는 번호: (1, 3, 5, 6, 7, 2, 8, 10)
'프로그래밍 언어 > Python' 카테고리의 다른 글
리스트와 튜플 차이점(파이썬) (0) | 2023.01.23 |
---|---|
튜플 슬라이싱[n:m](파이썬) (0) | 2023.01.23 |
튜플 길이(파이썬) (0) | 2023.01.23 |
튜플 in, not in 키워드(파이썬) (0) | 2023.01.23 |
튜플 인덱스(파이썬) (0) | 2023.01.23 |
Comments