member = {'basketball':5, 'soccer':11, 'baseball':9}
member['baseball'] # 검색
9
member = {'basketball':5, 'soccer':11, 'baseball':9}
member['volleyball'] = 7 # 새로운 아이템 설정
member['volleyball'] = 6 # 변경
print member
print len(member) # 아이템의 개수 반환
{'soccer': 11, 'basketball': 5, 'baseball': 9, 'volleyball': 6} 4
member = {'basketball':5, 'soccer':11, 'baseball':9}
del member['basketball'] # 항목 삭제
print member
{'soccer': 11, 'baseball': 9}
d = {}
d['str'] = 'abc'
d[1] = 4
d[(1,2,3)] = 'tuple'
d[[1,2,3]] = 'list' # 리스트는 키가 될 수 없다.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-7-74462e683085> in <module>() 3 d[1] = 4 4 d[(1,2,3)] = 'tuple' ----> 5 d[[1,2,3]] = 'list' # 리스트는 키가 될 수 없다. TypeError: unhashable type: 'list'
d[{1:2}] = 3 # 사전은 키가 될 수 없다.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-8-bac5c5696879> in <module>() ----> 1 d[{1:2}] = 3 # 사전은 키가 될 수 없다. TypeError: unhashable type: 'dict'
def add(a, b):
return a+b
def sub(a, b):
return a-b
action = {0: add, 1: sub} # 함수 이름을 사전의 값으로 사용
print action[0](4, 5)
print action[1](4, 5)
print
action2 = {add: 1, sub: 2} # 함수 이름을 사전의 키로 사용
print action2[add]
print add(4, 5)
9 -1 1 9
dict()
print dict(one=1, two=2)
print dict([('one', 1), ('two', 2)]) # 추후에 배우는 items()의 역변환에 해당
print dict({'one':1, 'two':2})
{'two': 2, 'one': 1} {'two': 2, 'one': 1} {'two': 2, 'one': 1}
keys = ['one', 'two', 'three']
values = (1, 2, 3)
print zip(keys, values) # zip(): 두 개의 자료를 순서대로 쌍으로 묶은 튜플들의 리스트 반환
print dict(zip(keys, values))
[('one', 1), ('two', 2), ('three', 3)] {'three': 3, 'two': 2, 'one': 1}
phone = {'jack':9465215, 'jin':1111, 'Joseph':6584321}
print phone.keys() #키의 리스트 반환
print phone.values() #값들의 리스트 반환
print phone.items() #(키, 값)의 리스트 반환
print
print 'jack' in phone #'jack'이 phone의 키에 포함되어 있는가?
print 'lee' in phone
['jin', 'Joseph', 'jack'] [1111, 6584321, 9465215] [('jin', 1111), ('Joseph', 6584321), ('jack', 9465215)] True False
phone = {'jack':9465215, 'jin':1111, 'Joseph':6584321}
p = phone # 사전 레퍼런스 복사. 사전 객체는 공유된다.
phone['jack'] = 1234 # phone을 변경하면
print phone
print p # p도 함께 변경된다.
print
ph = phone.copy() # 사전복사. 별도의 사전 객체가 마련된다.
phone['jack'] = 1111 # phone을 바꿔도
print phone
print ph # ph는 바뀌지 않는다.
{'jin': 1111, 'Joseph': 6584321, 'jack': 1234} {'jin': 1111, 'Joseph': 6584321, 'jack': 1234} {'jin': 1111, 'Joseph': 6584321, 'jack': 1111} {'jin': 1111, 'Joseph': 6584321, 'jack': 1234}
phone = {'a': [1,2,3], 'b': 4}
phone2 = phone.copy()
print phone
print phone2
print
phone['b'] = 100
print phone
print phone2
print
phone['a'][0] = 100
print phone
print phone2
{'a': [1, 2, 3], 'b': 4} {'a': [1, 2, 3], 'b': 4} {'a': [1, 2, 3], 'b': 100} {'a': [1, 2, 3], 'b': 4} {'a': [100, 2, 3], 'b': 100} {'a': [100, 2, 3], 'b': 4}
ph = {'jack':9465215, 'jin':1111, 'Joseph':6584321}
print ph.get('jack') # 'jack'에 대한 값을 얻는다. ph['jack']과 같다.
print ph.get('gslee') # 'gslee'에 대한 값을 얻는다. 값이 없는 경우 None반환
9465215 None
ph = {'jack':9465215, 'jin':1111, 'Joseph':6584321}
print ph['gslee'] # ph['gslee']는 키가 없는 경우 예외발생
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-11-00dc298a68ec> in <module>() 1 ph = {'jack':9465215, 'jin':1111, 'Joseph':6584321} ----> 2 print ph['gslee'] # ph['gslee']는 키가 없는 경우 예외발생 KeyError: 'gslee'
ph = {'jack':9465215, 'jin':1111, 'Joseph':6584321}
print ph.get('gslee', 5284) # 인수를 하나 더 제공하면 'gslee'가 없는 경우에 5284 리턴
print ph # 사전에는 변화가 없다
print
print ph.setdefault('gslee', 5284) # 'gslee'값을 꺼내되, 없으면 새로운 아이템으로 'gslee': 5284를 넣어주고 꺼낸다.
print ph # 'gslee':5284가 설정되어 있다.
print
print ph.popitem() # 임의의 아이템을 꺼낸다.
print ph
print ph.popitem() # 임의의 아이템을 꺼낸다.
print ph
print
print ph.pop('jack') # 키 값을 통해 해당 아이템을 지정하여 꺼낸다.
print ph
5284 {'jin': 1111, 'Joseph': 6584321, 'jack': 9465215} 5284 {'jin': 1111, 'Joseph': 6584321, 'jack': 9465215, 'gslee': 5284} ('jin', 1111) {'Joseph': 6584321, 'jack': 9465215, 'gslee': 5284} ('Joseph', 6584321) {'jack': 9465215, 'gslee': 5284} 9465215 {'gslee': 5284}
phone = {'jack':9465215, 'jin':1111, 'Joseph':6584321}
ph = {'kim':12312, 'lee': 9090}
phone.update(ph) #사전 phone의 내용을 ph으로 추가 갱신
print phone
print
phone.clear() #사전의 모든 입력을 없앤다.
print phone
{'jin': 1111, 'Joseph': 6584321, 'jack': 9465215, 'kim': 12312, 'lee': 9090} {}
print __name__ # 현재 모듈의 이름
print
import sys
print sys.__name__ # sys 모듈의 이름
__main__ sys
a = 1
b = 100
name = 'gslee'
dic = {'Python':'Good', 'Perl':'Not Good'}
print globals()
print locals()
def func():
a = 10
print globals()
print locals()
func()
class C:
x = 10
y = 20
print C.__dict__ # 클래스의 심볼 테이블을 얻는다.
print vars(C) # vars(C)는 내부적으로 C.__dict__ 의 값을 반환한다.
{'y': 20, 'x': 10, '__module__': '__main__', '__doc__': None} {'y': 20, 'x': 10, '__module__': '__main__', '__doc__': None}
c = C() # 클래스 C로부터 객체 c 생성
c.x = 100
c.y = 200
print c.__dict__ # 클래스 인스턴스의 심볼 테이블을 얻는다.
print vars(c)
print
print C.__dict__ # 클래스의 심볼 테이블을 얻는다.
print vars(C) # vars(C)는 내부적으로 C.__dict__ 의 값을 반환한다.
{'y': 200, 'x': 100} {'y': 200, 'x': 100} {'y': 20, 'x': 10, '__module__': '__main__', '__doc__': None} {'y': 20, 'x': 10, '__module__': '__main__', '__doc__': None}
def f():
pass
f.a = 1
f.b = 2
print f.__dict__ # 함수의 심볼 테이블을 얻는다.
{'a': 1, 'b': 2}
D = {'a':1, 'b':2, 'c':3}
for key in D.keys():
print key, D[key]
a 1 c 3 b 2
D = {'a':1, 'b':2, 'c':3}
for key in D:
print key, D[key]
a 1 c 3 b 2
for key, value in D.items():
print key, value
a 1 c 3 b 2
D = {'a':1, 'b':2, 'c':3}
items = D.items()
print items
print
items.sort()
print items
print
for k,v in items:
print k, v
[('a', 1), ('c', 3), ('b', 2)] [('a', 1), ('b', 2), ('c', 3)] a 1 b 2 c 3
d = {'one':1, 'two':2, 'three':3}
L = d.items()
print L
print
L.sort()
print L
[('three', 3), ('two', 2), ('one', 1)] [('one', 1), ('three', 3), ('two', 2)]
>>> def hap(x, y):
... return x + y ...
hap(10, 20)
30
(lambda x,y: x + y)(10, 20)
30
d = {'three':3, 'two':2, 'one':1}
L = d.items()
print L
print
L.sort(key=lambda item:item[1]) #lamda item:item[1] ==> f(item): return item[1]
print L
[('one', 1), ('three', 3), ('two', 2)] [('one', 1), ('two', 2), ('three', 3)]
d = {'three':3, 'two':2, 'one':1}
for key, value in sorted(d.items(), key=lambda item:item[1]):
print key, value
one 1 two 2 three 3
# file : directory.py
def print_menu():
print '1. 전화 번호 출력'
print '2. 전화 번호 추가'
print '3. 전화 번호 삭제'
print '4. 전화 번호 찾기'
print '5. 종료'
print
def print_dic(numbers):
print "전화번호: "
for name in numbers :
print "이름: ", name," \t번호: ",numbers[name]
print
def add_member(numbers):
print "이름과 번호 추가"
name = raw_input("이름: ")
phone = raw_input("번호: ")
numbers[name] = phone
def remove_member(numbers):
print "이름과 번호 삭제"
name = raw_input("이름: ")
if name in numbers:
del numbers[name]
else:
print name, " 은 없습니다."
def lookup_member(numbers):
print "번호 찾기"
name = raw_input("이름: ")
if name in numbers:
print "번호 : ", numbers[name]
else :
print name, "를 찾을 수 없습니다."
#------------------- 여기서 부터 실행된다.
numbers = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
menu_choice = input("번호를 입력해 주세요 (1-5):")
if menu_choice == 1:
print_dic(numbers)
elif menu_choice == 2:
add_member(numbers)
elif menu_choice == 3:
remove_member(numbers)
elif menu_choice == 4:
lookup_member(numbers)
if menu_choice != 5:
print_menu()
#arith.py
def add(a, b):
return a+b
def sub(a, b):
return a-b
def mul(a, b):
return a*b
def div(a, b):
return a/b
def choose_menu():
print 'What do you want to do?'
print 'add, sub, mul, div, quit'
return raw_input('Your choice: ')
# 키는 연산의 이름, 값은 함수 객체
menu = {'add':add, 'sub':sub, 'mul':mul, 'div':div}
choice = choose_menu()
while choice != 'quit':
if choice in menu :
x = input('first value : ')
y = input('Second value : ')
print menu[choice](x,y)
choice = choose_menu()
What do you want to do? add, sub, mul, div, quit Your choice: sub first value : 1 Second value : 2 -1 What do you want to do? add, sub, mul, div, quit
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'
print set(((1, 2), (1, 2))) # 동일한 내용의 튜플 2개는 집합 내에 한 개의 원소로 저장된다.
print set([(1, 2), (1, 2)])
set([(1, 2)]) set([(1, 2)])
set 연산 | 동일 연산자 | 내용 |
---|---|---|
len(s) | 원소의 개수 | |
x in s | x가 집합 s의 원소인가? | |
x not in s | x가 집합 s의 원소가 아닌가? | |
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 복사 |
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
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|B
print A
print
print A.intersection(B) #A와 B의 교집합
print A&B #A와 B의 교집합
print A
print
print A.difference(B) #A - B (차집합)
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, 10, 20, 30]) set([1, 2, 3, 4, 5, 6, 7, 8, 9]) set([4, 5, 6]) 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, 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() # Shallow 복사
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([])