t1 = () # 비어있는 튜플
t2 = (1,2,3) # 괄호 사용
t3 = 1,2,3 # 괄호가 없어도 튜플이 됨
print type(t1), type(t2), type(t3)
<type 'tuple'> <type 'tuple'> <type 'tuple'>
r1 = (1,) # 자료가 한 개일 때는 반드시 콤마가 있어야 한다.
r2 = 1, # 괄호는 없어도 콤마는 있어야 한다.
print type(r1)
print type(r2)
<type 'tuple'> <type 'tuple'>
t = (1, 2, 3)
print t * 2 # 반복
print t + ('PyKUG', 'users') # 연결
print t
print
print t[0], t[1:3] # 인덱싱, 슬라이싱
print len(t) # 길이
print 1 in t # 멤버십 테스트
(1, 2, 3, 1, 2, 3) (1, 2, 3, 'PyKUG', 'users') (1, 2, 3) 1 (2, 3) 3 True
t[0] = 100 # 튜플은 변경 불가능, 에러발생
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-ded308ebf8b1> in <module>() ----> 1 t[0] = 100 # 튜플은 변경 불가능, 에러발생 TypeError: 'tuple' object does not support item assignment
t = (12345, 54321, 'hello!')
u = t, (1, 2, 3, 4, 5) # 튜플 내부 원소로 다른 튜플을 가질 수 있음
print u
t2 = [1, 2, 3] # 튜플 내부 원소로 리스트 가질 수 있음
u2 = t2, (1, 2, 4)
print u2
t3 = {1:"abc", 2:"def"} # 튜플 내부 원소로 사전 가질 수 있음
u3 = t3, (1, 2, 3)
print u3
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) ([1, 2, 3], (1, 2, 4)) ({1: 'abc', 2: 'def'}, (1, 2, 3))
x, y, z = 1, 2, 3 # 튜플을 이용한 복수 개의 자료 할당
print type(x), type(y), type(z)
print x
print y
print z
<type 'int'> <type 'int'> <type 'int'> 1 2 3
x = 1
y = 2
x, y = y, x # 튜플을 이용한 두 자료의 값 변경
print x, y
2 1
t = 1, 2, 'hello'
x, y, z = t
a = ['foo', 'bar', 4, 5]
[x, y, z, w] = a
튜플과 리스트와의 공통점
리스트와 다른 튜플만의 특징
list() 와 tuple() 내장 함수를 사용하여 리스트와 튜플을 상호 변환할 수 있음
T = (1,2,3,4,5)
L = list(T)
L[0] = 100
print L
T = tuple(L)
print T
[100, 2, 3, 4, 5] (100, 2, 3, 4, 5)
def calc(a, b):
return a+b, a*b
x, y = calc(5, 4)
print 'id : %s, name : %s' % ('gslee', 'GangSeong')
id : gslee, name : GangSeong
d = {'one':1, 'two':2}
print d.items()
[('two', 2), ('one', 1)]
a = set([1, 2, 3])
print type(a)
print a
print
b = set((1, 2, 3))
print type(b)
print b
print
c = set({'a':1, 'b':2, 'c':3})
print type(c)
print c
print
d = set({'a':1, 'b':2, 'c':3}.values())
print type(d)
print d
<type 'set'> set([1, 2, 3]) <type 'set'> set([1, 2, 3]) <type 'set'> set(['a', 'c', 'b']) <type 'set'> set([1, 2, 3])
print set() # 빈 set 객체 생성
print set([1,2,3,4,5]) # 초기 값은 일반적으로 시퀀스 자료형인 리스트를 넣어준다.
print set([1,2,3,2,3,4]) # 중복된 원소는 한 번만 표현
print set('abc') # 문자열은 각 문자를 집합 원소로 지닌다.
print set([(1,2,3),(4,5,6)]) # 각 튜플은 원소로 가질 수 있음
print set([[1,2,3],[4,5,6]]) # 변경 가능 자료인 리스트는 집합의 원소가 될 수 없다.
set([]) set([1, 2, 3, 4, 5]) set([1, 2, 3, 4]) set(['a', 'c', 'b']) set([(4, 5, 6), (1, 2, 3)])
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-1-7f19fe538c1f> in <module>() 4 print set('abc') # 문자열은 각 문자를 집합 원소로 지닌다. 5 print set([(1,2,3),(4,5,6)]) # 각 튜플은 원소로 가질 수 있음 ----> 6 print set([[1,2,3],[4,5,6]]) # 변경 가능 자료인 리스트는 집합의 원소가 될 수 없다. TypeError: unhashable type: 'list'
set 연산 | 동일 연산자 | 내용 |
---|---|---|
len(s) | 원소의 개수 | |
x in s | x가 집합 s의 원소인가? | |
x not in s | x가 집합 s의 원소가 아닌가? |
A = set([1,2,3,4,5,6,7,8,9])
print len(A) # 집합의 원소의 수
print 5 in A # 멤버십 테스트
print 10 not in A # 멤버십 테스트
9 True True
set 연산 | 동일 연산자 | 내용 |
---|---|---|
s.issubset(t) | s <= t | s가 t의 부분집합인가? |
s.issuperset(t) | s >= t | s가 t의 슈퍼집합인가? |
s.union(t) | s | t | 새로운 s와 t의 합집합 |
s.intersection(t) | s & t | 새로운 s와 t의 교집합 |
s.difference(t) | s - t | 새로운 s와 t의 차집합 |
s.symmetric_difference(t) | s ^ t | 새로운 s와 t의 배타집합 |
s.copy() | 집합 s의 shallow 복사 |
B = set([4,5,6,10,20,30])
C = set([10,20,30])
print C.issubset(B) # C가 B의 부분집합?
print C <= B
print B.issuperset(C) # B가 C를 포함하는 집합?
print B >= C
print
True True True True
A = set([1,2,3,4,5,6,7,8,9])
B = set([4,5,6,10,20,30])
print A.union(B) # A와 B의 합집합
print A
print
print A.intersection(B) # A와 B의 교집합
print A
print
print A.difference(B) # A - B (차집합)
print A
print
print A.symmetric_difference(B) # 베타집합. A와 B의 합집합에서 교집합의 원소를 제외한 집합
print A
set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]) set([1, 2, 3, 4, 5, 6, 7, 8, 9]) set([4, 5, 6]) set([1, 2, 3, 4, 5, 6, 7, 8, 9]) set([1, 2, 3, 7, 8, 9]) set([1, 2, 3, 4, 5, 6, 7, 8, 9]) set([1, 2, 3, 7, 8, 9, 10, 20, 30]) set([1, 2, 3, 4, 5, 6, 7, 8, 9])
A = set([1,2,3,4,5,6,7,8,9])
B = set([4,5,6,10,20,30])
print A | B # A와 B의 합집합
print A
print
print A & B # A와 B의 교집합
print A
print
print A - B #A - B (차집합)
print A
print
print A.symmetric_difference(B) # 베타집합. A와 B의 합집합에서 교집합의 원소를 제외한 집합
print A ^ B
print A
set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]) set([1, 2, 3, 4, 5, 6, 7, 8, 9]) set([4, 5, 6]) set([1, 2, 3, 4, 5, 6, 7, 8, 9]) set([1, 2, 3, 7, 8, 9]) set([1, 2, 3, 4, 5, 6, 7, 8, 9]) set([1, 2, 3, 7, 8, 9, 10, 20, 30]) set([1, 2, 3, 7, 8, 9, 10, 20, 30]) set([1, 2, 3, 4, 5, 6, 7, 8, 9])
A = set([1,2,3,4,5,6,7,8,9])
D = A.copy()
print D
print
print A == D #자료값 비교
print A is D #객체 동등성 비교
set([1, 2, 3, 4, 5, 6, 7, 8, 9]) True False
A = set([1,2,3,4,5,6,7,8,9])
print A[0]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-a0fca37959a3> in <module>() 1 A = set([1,2,3,4,5,6,7,8,9]) ----> 2 print A[0] TypeError: 'set' object does not support indexing
print A[1:4]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-13-795e14598526> in <module>() ----> 1 print A[1:4] TypeError: 'set' object has no attribute '__getitem__'
print A.sort()
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-11-9fbe6777337f> in <module>() ----> 1 print A.sort() AttributeError: 'set' object has no attribute 'sort'
print list(A)
print tuple(A)
[1, 2, 3, 4, 5, 6, 7, 8, 9] (1, 2, 3, 4, 5, 6, 7, 8, 9)
A = set([1,2,3,4,5,6,7,8,9])
for ele in A:
print ele,
1 2 3 4 5 6 7 8 9
set 연산 | 동일 연산자 | 내용 |
---|---|---|
s.update(t) | s |= t | s와 t의 합집합을 s에 저장 |
s.intersection_update(t) | s &= t | s와 t의 교집합을 s에 저장 |
s.difference_update(t) | s -= t | s와 t의 차집합을 s에 저장 |
s.symmetric_difference_update(t) | s ^= t | s와 t의 배타집합을 s에 저장 |
s.add(x) | 원소 x를 집합 s에 추가 | |
s.remove(x) | 원소 x를 집합 s에서 제거, 원소 x가 집합 s에 없으면 예외 발생 | |
s.discard(x) | 원소 x를 집합 s에서 제거 | |
s.pop() | 임의의 원소를 집합 s에서 제거, 집합 s가 공집합이면 예외 발생 | |
s.clear() | 집합 s의 모든 원소 제거 |
A = set([1,2,3,4])
B = set([3,4,5,6])
A.update(B) # A에 B 집합의 원소를 추가 시킴
print A
A.intersection_update([4,5,6,7,8]) # &=
print A
A.difference_update([6,7,8]) # -=
print A
A.symmetric_difference_update([5,6,7]) # ^=
print A
A.add(8) # 원소 추가
print A
A.remove(8) # 원소 제거
print A
set([1, 2, 3, 4, 5, 6]) set([4, 5, 6]) set([4, 5]) set([4, 6, 7]) set([8, 4, 6, 7]) set([4, 6, 7])
A.remove(10) # 없는 원소를 제거하면 KeyError 발생
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-21-1bcb28846ad3> in <module>() ----> 1 A.remove(10) #없는 원소를 제거하면 KeyError 발생 KeyError: 10
A.discard(10) # remove와 같으나 예외가 발생하지 않음
A.discard(6) # 원소 6제거
print A
A.pop() # 임의의 원소 하나 꺼내기
print A
A = set([1,2,3,4])
A.clear() # 원소들 없애기
print A
set([4, 7]) set([7]) set([])
참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일