~cpp t = () # 공 튜플 t = (1,2,3) t = 1,2,3 # 괄호가 없어도 튜플이됨 r = (1,) r = 1, # r=1로 해석되지 않기 위함 t[0]=100 # 허용 안됨. 에러 발생 * 튜플을 이용하여 좌우변에 복수개의 자료를 치환할 수 있다. >>> x,y,z=1,2,3 * 이를 이용하여 두 변수의 값을 쉽게 치환할 수 있다. >>> x = 1 >>> y = 2 >>> x, y = y, x >>> x, y (2,1)
~cpp t = 1,2,'hello'튜플 언패킹 - 반대로, 튜플에서 데이터를 꺼내오는 것을 튜플 언패킹이라고 한다.
~cpp x,y,z = t
~cpp >>> T = (1,2,3,4,5) >>> L = list(T) >>> L[0] = 100 >>> L [100, 2, 3, 4, 5] >>> T = tuple(L) >>> T (100, 2, 3, 4, 5)
~cpp
>>> def calc(a,b):
return a+b, a*b
>>> x, y = calc(5, 4)
~cpp
>>> print 'id : %s, name : %s' % ('gslee','GangSeong')
id : gslee, name : GangSeong
~cpp >>> apply(calc, (4,5)) (9,20)
~cpp
>>> d = {'one':1, 'two':2}
>>> d.items()
[('one',1), ('two',2)]
~cpp
>>> dic = {} # dic이라는 이름으로 비어있는 사전을 만든다.
>>> dic['dictionary'] = '1. A reference book containing an alphabetical list of words, ...'
>>> dic['python'] = 'Any of various nonvenomous snakes of the family Pythonidae, ...'
>>> dic['dictionary'] # dic아, ‘dictionary’가 뭐니?
'1. A reference book containing an alphabetical list of words, ...'
~cpp
>>> member = {'basketball' :5, 'soccer':11, 'baseball':9}
>>> member['baseball'] # 검색
9
>>> member['volleyball'] = 7 # 항목 추가
>>> member
{'soccer' : 11, 'volleyball' : 7 'baseball' : 9 , 'basketball' : 5}
>>> len(member)
4
>>> del member['basketball'] # 항목 삭제
~cpp
>>> def add(a,b):
return a+b
>>> def sub(a,b):
return a-b
>>> action = {0:add, 1:sub}
>>> action[0](4,5)
9
>>> action[1](4,5)
-1
~cpp
>>> a = d # 사전 레퍼런스 복사. (사전 객체는 공유된다)
>>> a = d.copy() # 사전 복사. (별도의 사전 객체가 마련된다.)
>>> phone = {'jack': 232412, 'jim':1111, 'Joseph' : 234632}
>>> p = phone
>>> phone['jack'] = 1234
>>> phone
{'jack': 1234, 'jim':1111, 'Joseph' : 234632}
>>> p
{'jack': 1234, 'jim':1111, 'Joseph' : 234632}
>>> ph = phone.copy()
>>> phone['babo'] = 5324
>>> phone
{'jack': 1234, 'jim':1111, 'Joseph' : 234632, 'babo' : 5324}
>>> ph
{'jack': 1234, 'jim':1111, 'Joseph' : 234632}
7. D.get(key , x) : 값이 존재하면 Dkey 즉 값을 리턴, 아니면 x를 리턴~cpp
>>> D = {'a':1, 'b':2 ,'c':3}
>>> for key in D.keys():
print key, D[key]
b 2
c 3
a 1
~cpp
>>> items = D.items()
>>> items.sort()
>>> items
[('a', 1), ('b', 2) , ('c', 3)]
>>> for k,v in items:
print k, v
a 1
b 2
c 3
~cpp
>>> D = {'a':1, 'b':2, 'c':3}
>>> for key in D:
print key, D[key]
a 1
c 3
b 2