7. 분자
sequence, set, dict 타입은 다양한 원소들을 가지
므로 분자 구조를 이름
Set타입은 내부적으로는 index나 key를 사용하지 않
음
Object head
items
Index/key
Index/key
Index/key
Index/key
value
value
value
value
8. 분자 dict 예시
dict를 상속받아 __init__ , __getattr__,
__setattr__메소드를 override 처리하여 멤버연
산자(.)도 사용이 가능하도록 처리
class D(dict) :
def __init__(self,obj) :
self.update(obj)
def __getattr__(self,name) :
return self[name]
def __setattr__(self,name, value) :
self[name] = value
d = D(dict(k=5))
d.l =1
print d
print d.has_key('l'), d['l']
print type(d)
{'k': 5, 'l': 1}
True 1
<class '__main__.D'>
9. 분자 list 예시
list를 상속받아 __init__ 메소드를 override 처리
class L(list) :
def __init__(self,obj) :
self.append(list(obj))
l = L([1,2,3])
print type(l), l
l.append(1)
print type(l), l
<class '__main__.L'> [[1, 2, 3]]
<class '__main__.L'> [[1, 2, 3], 1]
11. 객체 구조
int를 상속받아 __init__ 메소드를 override를 해
서 int 처럼 처리
class atomic(int) :
def __init__(self,obj) :
self = int(obj)
def __add__(self,obj) :
value = int(self) + int(obj)
return atomic(value)
Object head
value
i = atomic(1)
print type(i), i
i = atomic(i +1)
print type(i), i
j = i.__add__(10)
print type(j), j
<class '__main__.atomic'> 1
<class '__main__.atomic'> 2
<class '__main__.atomic'> 12
__init__ 인스턴스 생성
Value 값 세팅
13. 타입 특성
데이터를 관리하는 기준이며 파이썬은 최상위 타입
을 Object로 선정해서 모든 것을 object instance로
처리
>>> type(object)
<type 'type'>
>>> type(1)
<type 'int'>
>>> isinstance(1,object)
True
>>>
Object를 최상위 클래스 객체이며 이
를 상속받아 구현
숫자 1도 실제 자연수라는 클래스객
체에서 생성된 객체라서 Object이 인
스턴스 객체
14. Builtin type 특성
객체 내부에 정해진 값이 변경이 가능한지를 구분
=> 컨테이너 타입 중에 실제 값이 정해지지 않은
경우 요소들을 변경이 가능
변경불가(immutable) : int, float, complex,
str/unicode/bytes, tuple, frozenset
변경가능(mutable) : list, dict, set, bytes-array
15. Data types 이해하기
int 등 data type의 키워드는 클래스 객체이고
type 클래스 객체를 구현해서 처리
>>> int.__class__.__name__
'type'
>>> intobj =1
>>> intobj.__class__.__name__
'int'
>>> isinstance(intobj.__class__, type)
True
>>> intobj2 = int(1)
>>> intobj2
1
>>> intobj2.__class__.__name__
'int'
>>> type.__class__.__name__
'type'
>>>
생성된 int 타입이 type 클
래스 객체를 상속여부 확인
16. Value and Type : 예시
다양한 타입에 대한 타입과 값을 함수를 통해 처리하는 법
obj.__class__.__name__
• obj.__class__의 값은 타입 클래스의 인스턴스
• 타입클래스의 __name__속성은 타입에 대한 스트링 관리
def typeof(obj) :
return obj.__class__
def valueof(obj) :
if obj.__class__ == type(obj) :
print(eval(obj.__class__.__name__ + '(obj)'))
return eval(obj.__class__.__name__ + '(obj)')
print(typeof(1))
print(valueof(1))
print(typeof(1.1))
print(valueof(1.1))
print(typeof([1,2]))
print(valueof([1,2]))
#결과값
<type 'int'>
1
1
<type 'float'>
1.1
1.1
<type 'list'>
[1, 2]
[1, 2]
18. Mutable & immutable
Values 내부의 값을 변경이 가능한지 점검하여 값을 변
경.
특히 variables, 함수 파라미터에 복사할 경우 실제 값 객
체가 변경가능여부에 따라 다른 경우가 발생함
Mutable은 주로 리스트, 딕셔너리 타입으로 내부 값인
요소에 추가하는 것이므로 변수나 함수 파라미터로 사용
해도 변경( swallow copy 사용)
Mutable 처리할 경우 처음이 값이 변경되지 않으려면 참
조만 복사하지 말고 전체 값을 복사해야 별도의 참조가
생겨 다른 값 객체로 인식함(deepcopy 이용)
19. Mutable & immutable 예시
ismutable 함수를 만들어서 실제 값들이 변경여부를 점검한
후에 처리할 수 있으면 좋다
#함수를 정의해서 각 타입에 대한 갱신여부를 확인
def ismutable(obj) :
result = True
#타입을 문자열로 가져오기
com = obj.__class__.__name__
if com not in [ 'int','float','str','tuple'] :
result = False
return (com,result)
#실행
print 'str is ', ismutable('a')
print 'list is',ismutable([])
print 'tuple is',ismutable((1,))
print 'dict is',ismutable({})
print 'object is',ismutable(object)
print 'function is',ismutable(lambda x:x)
# 결과값
str is ('str', True)
list is ('list', False)
tuple is ('tuple', True)
dict is ('dict', False)
object is ('type', False)
function is ('function', False)
21. Type conversion
변수에서 참조하는 타입을 자신의 필요한 타입으로 변경이 필요할 경우 사용
파이썬에 제공되는 함수들을 이용해서 사용하면 됨
>>> v = 1
>>> str(v)
'1'
>>> float(str(v))
1.0
>>> int(str(v))
1
>>> x = int()
>>> x
0
>>> y = str()
>>> y
''
>>> z = float()
>>> z
0.0
>>>
타입 함수를 이용해서 변수에 할
당하면 초기값을 세팅
타입 함수를 이용해서 변수에 적
절한 타입으로 변환
22. Type conversion
파라미터를 하나 받아 객체를 실행하면 타입전환 처
리함
int()
float()
str()
list()
dict()
tuple()
set()
>>> int
<type 'int'>
>>> float
<type 'float'>
>>> str
<type 'str'>
>>> list
<type 'list'>
>>> dict
<type 'dict'>
>>> tuple
<type 'tuple'>
>>> set
<type 'set'>
>>>
23. String에서 integer 변환
문자열은 문자와 숫자로 구성될 수 있으므로 숫
자여부를 확인하고 형변환을 해야 함
>>> # string을 내부를 숫자로
>>> v = '1‘
>>> #string 내장 메소드로 숫자여부 체크
>>> if v.isdigit() :
... s = int(v)
... else :
... s = 0
...
>>> s
1
25. 숫자타입
숫자에 대한 객체를 관리하는 데이터 타입
Numberic Types
int
float
long
complex
>>> id(1)
5939944
>>> v = 1
>>> type(v)
<type 'int'>
>>> id(v)
5939944
>>>
숫자타입도 하나의 객체이므로 1 이 생성
되면 동일한 context 내에서는 동일한 객체
id를 가지고 사용
26. 숫자타입 - 기본처리
숫자 타입에 기본으로 처리 되는 함수, operator
Operation Result Notes
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x / y quotient of x and y
x // y (floored) quotient of x and y
x % y remainder of x / y
-x x negated
+x x unchanged
abs(x) absolute value or magnitude of x
int(x) x converted to integer
long(x) x converted to long integer
float(x) x converted to floating point
complex(re,im)
a complex number with real part re, imaginary part im. im defaults to z
ero.
c.conjugate() conjugate of the complex number c
divmod(x, y) the pair (x // y, x % y)
pow(x, y) x to the power y
x ** y x to the power y
28. Sequence 타입
다양한 객체의 값을 원소로 값는 데이터 타입
Sequenec Types
String/unicode
Buffer/range
List/tuple
참조 container
참조
참조
값
container
** string 일경우 값만
처리
Elements 관리
29. Sequence 타입- 기본처리
Sequence 타입에 기본으로 처리 되는 함수,
operator
Operation Result Notes
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s + t the concatenation of s and t
s * n , n * s n shallow copies of s concatenated
s[i] i'th item of s, origin 0
s[i:j] slice of s from i to j
s[i:j:k] slice of s from i to j with step k
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
30. Sequence-Accessing Values
Sequence Type(String, List, Tuple)은 변수명[index]로 값을 접
근하여 가져옴
변수에는 Sequence Instance이 참조를 가지고 있고 index를 이
용하여 값들의 위치를 검색
>>> l = [0,1,2,3]
>>> l[0]
0
>>> s = "string"
>>> s[0]
's'
>>> t = (0,1,2,3)
>>> t[0]
0
>>>
31. Sequence-Updating Values
변수에는 Sequence Instance이 참조를 가지고 있고
index를 이용하여 값들의 위치를 검색하고 할당값을 변
경. 단, Mutable 객체인 List타입만 기존 값을 변경됨
>>> l
[0, 1, 2, 3]
>>> l[0] = 100
>>> l
[100, 1, 2, 3]
>>> t
(0, 1, 2, 3)
>>> t[0] = 100
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not
support item assignment
>>>
>>> s
'string'
>>>
>>> s[0] = 'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not
support item assignment
List type Tuple type String type
32. Sequence- 내장함수 이용하기
Sequence 내장함수를 이용한 sorted, reversed,
enumerate, zip을 처리
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe
>>> l1 = [1,2,3,4]
>>> la = ['a','b','c','d']
>>> for k,v in zip(l1,la) :
... print k, v
...
1 a
2 b
3 c
4 d
>>>
>>> for i in reversed(xrange(1,10,2)):
... print i
...
9 7 5 3 1
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange',
'banana']
>>> for f in sorted(set(basket)):
... print f
...
apple banana orange pear
enumerate() zip()
reversed() sorted()
33. Sequence- 내장함수
내장함수 중에 tuple 타입을 처리
Function Description
cmp(seq1, seq2) 시퀀스이 동일할 경우 타입내의 원소를 비교
len(seq) 시퀀스 타입의 원소 갯수
max(seq) 시퀀스 타입의 원소중에 최고 값
min(seq) 시퀀스 타입의 원소중에 최소 값
str(seq) 시퀀스 타입을 문자열 전환
type(seq) 시퀀스 타입이 타입을 표시
35. Sequence slicing
Sequence 타입(string, list, tuple)에 대한 내부 원소들
을 추출하기 위해 slicing을 사용
[ 시작위치:종료위치:간격]
>>> mystring[0:5] 'hello' >>> mystring[6:-1] 'worl'
36. Sequence slicing-역방향
문자열을 역으로 처리하기
>>> s = 'hello'
>>> s[-3:]
'llo'
>>> s[:-3]
'he'
>>> s[-1:-3]
''
>>> s[-1:0]
''
>>> s[-1:-3:-1]
'ol'
>>>
역방향으로 처리하기 위해서는
변수명[시작점:종료점:스텝] 정의
시 역방향으로 정의하고 스템도
마이너스로 표시하면 역으로 처
리
38. Sequence-Updating String
String에 대한 update는 기본적으로 새로운
String Instance 만드는 것
>>> s
'string'
>>> id(s)
6122176
>>> v = "updating " + s
>>> id(v)
106043176
>>> v
'updating string'
>>>
>>> s
'string'
>>>
39. String-raw string
Operator Description Example
r/R
Raw String (whitespace 등도 문자열 처
리) 표시
print r'n' or print R’n’ ‘n,
prints “n “ 빈공칸을 출력
문자열 값을 그대로 사용하기 위해 지정해서 사
용함
40. builtin내장함수
s = “python”
Method example Description
max(str) max(s)
'y'
문자열 내의 최고 값
min(str) min(s)
'h'
문자열 내의 최소 값
len(str) len(s)
6
문자열 길이
41. String-operator
Operator 내장 메소드 Description Example
+ __add__ 문자열과 문자열이 연결 >>> "p".__add__("i")
'pi'
>>> "p"+"i"
'pi'
>>>
* __mul__ 문자열의 반복 "p".__mul__(4)
‘pppp'
"p"*4
'pppp'
[] [] 문자열 참조를 위한 슬라이스 기호 "python".__getitem__(1)
'y'
"python"[1]
'y'
[ : ] [ : ] 슬라이스에 대한 범위를 지정 "python".__getslice__(1,2)
'y'
"python"[1:2]
y'
in __contains__ 내부의 요소로 가지고 있는지 확인 "python".__contains__("p")
True
"p" in "python"
True
not in 내부의 요소가 아닌 경우 확인
42. String-operator
Operator 내장 메소드 Description Example
== __eq__ 두 문자열이 동등 "p".__eq__("p")
True
"p" == "p"
True
<= __ge__ 다른 문자열이 크거나 같다 "a".__ge__("a")
True
"a" <= "a"
True
< __gt__ 다른 문자열보다 크다 "a" < "b"
True
"b".__gt__("a")
True
>= __le__ 슬라이스에 대한 범위를 지정 "b" >= "b"
True
"b".__le__("b")
True
> __lt__ 내부의 요소로 가지고 있는지 확인 "b" > "a"
True
"a".__lt__("b")
True
!= __ne__ 내부의 요소가 아닌 경우 확인 "b" != "a"
True
"a".__ne__("b")
True
43. Sequence-String 메소드(1)
s = “python”
Method example Description
capitalize() s.capitalize()
'Python'
첫문자를 대문자로 전환
center(width, fillchar) s.center(10,'x')
'xxpythonxx'
스페이스를 만들고 글자를 센터에 놓고 빈공칸을 특
정 문자로 채움
count(str, beg=
0,end=len(string))
s.count('y')
1
문자열 내의 문자나 문자열에 대한 개수를 셈
decode(encoding='UTF-
8',errors='strict')
문자열을 특정 encoding 타입으로 복호화 errors시
ignore/replace로 처리 가능
encode(encoding='UTF-
8',errors='strict')
문자열을 특정 encoding 타입으로 암호화 errors시
ignore/replace로 처리 가능
endswith(suffix, beg=0,
end=len(string))
s.endswith("on")
True
문자열 suffix를 비교
expandtabs(tabsize=8) "1t2t".expandtabs(4)
Out[70]: '1 2 '
탭간의 간격을 최대 8이고 사이즈를 줄이면 됨
44. Sequence-String 메소드(2)
s = “python”
Method example Description
find(str, beg=0
end=len(string))
s.find("th")
2
부분 문자열이 시작하는 위치 단 검색이 안 될 경우 -1
index(str, beg=0, end=len(
string))
s.index("th")
2
find()메소드와 동일 단 검색이 안 될 경우 exception 처
리 ValueError: substring not found
isalnum() s.isalnum()
True
알파벳과 숫자 조합인지 확인
isalpha() s.isalpha()
True
알파벳 확인
isdigit() "1234".isdigit()
True
숫자 확인
islower() "Python".lower()
'python'
소문자여부 확인하여 전체를 소문자 처리
isspace() " ".isspace()
True
Whitespace로만 구성된 문자열 여부 확인
45. Sequence-String 메소드(3)
s = “python”
Method example Description
istitle() s_t = s.capitalize()
s_t.istitle()
True
"titlecased" 에 대한 여부 확인 단어의 첫글자는 무조건
대문자이어야 함
isupper() s_s = s.upper()
s_s.isupper()
True
모든 문자가 대문자 여부 확인
join(seq) ".".join(s)
'p.y.t.h.o.n'
문자열을 새롭게 조합하는 것
ljust(width[, fillchar]) s.ljust(10,'x')
'pythonxxxx'
스페이스 공간을 만들고 기존 문자열을 왼쪽부터 시작하
고 빈칸에 문자로 채운다
lower() s.lower()
'python'
대문자를 소문자로 전환
lstrip() " a ".lstrip()
'a '
좌측 whitespace 제거
partition(sep) "abcde".partition('bcd')
('a', 'bcd', 'e')
partition(sep) -> (head, sep, tail)
분리자에 의해 헤드와 테일로 구분
46. Sequence-String 메소드(4)
s = “python”
Method example Description
replace(old, new [, max]) s.replace('py',"jpy")
'jpython'
기존 문자열을 새로운 문자열로 전환.
rfind(str, beg=0,end=len(
string))
s.rfind('p')
0
find()와 동일하나 오른쪽부터 찾는다.
rindex( str, beg=0,
end=len(string))
s.rindex('n')
5
index()와 동일하나 오른쪽부터 찾는다.
rjust(width,[, fillchar]) s.rjust(10,'x')
'xxxxpython'
스페이스 공간을 정하고 오른쪽부터 문자열을 배
치하고 빈공간에 문자로 표시
rpartition(sep) "abcde".rpartition("bcd")
('a', 'bcd', 'e')
rpartition(sep) -> (head, sep, tail)
분리자에 의해 헤드와 테일로 구분
rsplit([sep [,maxsplit]]) "a,b,c,".rsplit(',')
['a', 'b', 'c', '']
문자열의 분리자로 분리하고 리스트로 출력
rstrip() "abc ".rstrip()
'abc'
오른쪽 whitespace 모두 제거
47. Sequence-String 메소드(5)
s = “python”
Method example Description
split(str="", num=string.c
ount(str))
"a,b,c,".split(',')
['a', 'b', 'c', '']
문자열을 구분자에 의해 리스트로 분리
splitlines( num=string.co
unt('n'))
"anbn".splitlines(2)
['an', 'bn']
개행문자의 개수에 따라 리스트로 문장 분리
startswith(str,
beg=0,end=len(string))
s.startswith("py")
True
문자열의 접두사를 확인
strip([chars]) " abc ".strip(' ')
'abc'
lstrip() and rstrip()를 실행
swapcase() s.swapcase()
'PYTHON'
소문자일 경우는 대문자로 대문자일 경우는 소문
자로 전환
title() s.title()
'Python'
문자열을 title 폼으로 전환
translate(table, deletech
ars="")
'read this short text'.translate(N
one, 'aeiou')
'rd ths shrt txt'
Translates string according to translation
table str(256 chars), removing those in the del
string.
48. Sequence-String 메소드(6)
s = “python”
Method example Description
upper() s.upper()
'PYTHON'
소문자를 대문자로 전환.
zfill (width) s.zfill(10)
'0000python'
문자를 왼쪽부터 채우고 나머지 빈공칸을 0으로 채움
49. String-escape 문자
Backslash notation Hexadecimal character Description
a 0x07 Bell or alert
b 0x08 Backspace
000 널문자
cx Control-x
C-x Control-x
e 0x1b Escape
f 0x0c Formfeed
M-C-x Meta-Control-x
n 0x0a Newline 은 라인피드 (Line Feed) 는 커서의 위치를 아랫줄로 이동
nnn Octal notation, where n is in the range 0.7
r 0x0d Carriage return은 현재 위치를 나타내는 커서 를 맨 앞으로 이동
s 0x20 Space
t 0x09 Tab
v 0x0b Vertical tab
x Character x
xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F
문자 ""
' 단일 인용부호(')
" 이중 인용부호(")
51. Sequence - List 기본 처리
List 타입에 대한 기본 처리
Python Expression Results Description
l=[1,2,3] l.append(4) [1, 2, 3, 4] 리스트에 원소 추가
del l[3] [1, 2, 3] 리스트에 원소 삭제
len([1, 2, 3]) 3 Length 함수로 길이 확인
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] 리스트를 합치니 Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 리스트 내의 원소를 Repetition
3 in [1, 2, 3] True 리스트 내의 원소들이 Membership
for x in [1, 2, 3]: print x, 1 2 3 리스트의 원소들을 반복자 활용 - Iteration
52. Sequence-List 용 내장함수
내장함수중에 리스트 타입을 처리
Function Description
cmp(list1, list2) Compares elements of both lists.
len(list) Gives the total length of the list.
max(list) Returns item from the list with max value.
min(list) Returns item from the list with min value.
list(seq) Converts a tuple into list.
str(list) Produces a printable string representation of a list
type(list) Returns the type of the passed variable. If passed variable is
list, then it would return a list type.
53. Sequence-List class 구조 확인
list는 하나의 class object로 제공
>>> list
<type 'list'>
>>> id(list)
505560280
>>>
>>>
>>> l1 = list()
>>> id(l1)
106593376
>>> isinstance(l1,list)
True
>>>
list의 인스턴스를 생성하고
isinstance 함수를 이용하여
인스턴스 여부 확인
54. Sequence-list 메소드(1)
l = [1,2,3,4]
Method example Description
list.append(obj) l.append(5)
l
[1, 2, 3, 4, 5]
리스크객체에 추가
list.count(obj) l.count(1)
1
리스크 원소에 대한 갯수
list.extend(seq) l.extend([6,7,8])
l
[1, 2, 3, 4, 5, 6, 7, 8]
리스트에 시퀀스 타입을 추가
list.index(obj) l.index(2)
1
리스트 내의 원소의 인덱스
list.insert(index,obj) l.insert(2,7)
L
[1, 2, 7, 3, 4]
리스트 내에 인덱스 위치에 삽입
list.pop(obj=list[-1]) l.pop(2)
7
인덱스가 가르치는 곳에 원소를 삭제, 인덱스가 없
으면 제일 끝을 제거
55. Sequence-list 메소드(2)
l = [1,2,3,4]
Method example Description
list.remove(obj) l.remove(4)
l
[1, 2, 3]
리스트를 원소의 값으로 제거
list.reverse() l.reverse()
l
[4, 3, 2, 1]
리스트를 반대방향으로 소트
list.sort([func]) l.sort()
l
[1, 2, 3, 4]'
리스트를 순차적으로 소트 처리 파라미터로 함수를
제공할 경우 함수에 정한 순서대로 소트
56. Sequence-List Comprehension
리스트 정의시 값을 정하지 않고 호출 시 리스트
내의 값들이 처리되도록 구성
A = [ 표현식 for i in sequence if 논리식]
>>> squares = []
>>> for x in (10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> squares = [x**2 for x in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>
57. Sequence-List로 stack 처리
Stack은 LIFO(last in first out)으로 List를 이용하
여 원소 추가(append메소드) 및 삭제(pop메소드)
로 간단하게 구성
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack [3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack [3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack [3, 4]
58. Sequence-List로 queue 처리
queue은 FIFO(first in first out)으로 List를 이용
하여 원소 추가(append메소드) 및 삭제
(reverse,pop메소드)로 간단하게 구성
>>> l = [1,2,3,4]
>>> l.reverse()
>>> l
[4, 3, 2, 1]
>>> l.pop()
1
>>> l.reverse()
>>> l
[2, 3, 4]
>>>
60. Sequence - Tuple 기본 처리
tuple타입에 immutable 타입으로 내부 원소에 대해
갱신이 불가능하여 리스트처리보다 제한적
Slicing은 String 처럼 처리가능
Python Expression Results Description
T =(1,) (1,) 튜플의 원소가 하나인 경우 생성 꼭 한 개일 경우는
뒤에 꼼마(,)를 붙여야 함
T = (1,2,3,4) (1, 2, 3, 4) 튜플 생성
len((1, 2, 3)) 3 Length 함수로 길이 확인
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) 튜플을 합치기 Concatenation
('Hi!‘) * 4 'Hi!Hi!Hi!Hi!' 튜플의 반복을 string으로 표시
3 in (1, 2, 3) True 튜플 내의 원소들이 Membership
for x in (1, 2, 3): print x, 1 2 3 튜플의 원소들을 반복자 활용 - Iteration
62. Set 타입
중복을 허용하지 않고, 순서가 없음 (unordered)
교집합(&), 합집합(|), 차집합(-) 연산 처리
Set: mutable set
Frozenset: immutable set
63. Set 타입 – 생성시 주의
Set()으로 생성시 파라미터는 1개만 받는다. 리스트
등 mutable 객체를 요소로 처리할 수 없다.
그래서 튜플로 처리
>>> s = set([1],[2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: set expected at most 1 arguments, got
2
>>> s = set(([1],[2]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>
>>> s = set(((1),(2)))
>>> s
set([1, 2])
>>>
>>> s = set({'a':1})
>>> s
set(['a'])
Set은 구조상 내부 요소
가 변경이 가능한 값으
로 구성할 수 없다
Set에 dictionary로 생
성시 요소는 변경할 수
없는 immutable타입만
생성함
64. Set 타입 – Set 생성 및 추가
Set type은 mutable 타입이므로 생성 후 원소를
추가나 삭제가 가능
>>>
>>> s = set([1,2,3])
>>> s
set([1, 2, 3])
>>> s1 = set([1,2,3,3,4,4])
>>> s1
set([1, 2, 3, 4])
>>> s.add(5)
>>> s
set([1, 2, 3, 5])
>>> s1.add(5)
>>> s1
set([1, 2, 3, 4, 5])
>>>
65. Set 타입 – FrozenSet 생성 및 추가
FrozenSet type은 immutable 타입이므로 생성
후 원소를 추가나 삭제가 불가능
>>> s = frozenset([1,2,3])
>>> s
frozenset([1, 2, 3])
>>> s.add(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute
'add'
>>>
66. Set 타입- 기본처리
Operation Equivalent Result
len(s) cardinality of set s
x in s test x for membership in s
x not in s test x for non-membership in s
s.issubset(t) s <= t test whether every element in s is in t
s.issuperset(t) s >= t test whether every element in t is in s
s.union(t) s | t new set with elements from both s and t
s.intersection(t) s & t new set with elements common to s and t
s.difference(t) s - t new set with elements in s but not in t
s.symmetric_difference(t) s ^ t
new set with elements in either s or t but not b
oth
s.copy() new set with a shallow copy of s
67. Set 타입- set 확장처리
Operation Equivalent Result
s.update(t) s |= t update set s, adding elements from t
s.intersection_update(t) s &= t
update set s, keeping only elements found in bot
h s and t
s.difference_update(t) s -= t update set s, removing elements found in t
s.symmetric_difference_update(t) s ^= t
update set s, keeping only elements found in eithe
r s or t but not in both
s.add(x) add element x to set s
s.remove(x) remove x from set s; raises KeyError if not present
s.discard(x) removes x from set s if present
s.pop()
remove and return an arbitrary element from s; rais
es KeyError if empty
s.clear() remove all elements from set s
69. Map 타입-dictionary
Key/Value로 원소를 관리하는 데이터 타입
요소들은 변경가능하므로 변수에 복사시
참조 container
Name 1 값
Name 2
contain
er
참조
참조
:
:
Dictionary Type
70. Map 타입 - Accessing Elements
Key/Value로 원소를 관리하므로 Key를 가지고
원소를 검색
>>> dd = {'name': 'dahl', 'age':50}
>>> dd
{'age': 50, 'name': 'dahl'}
>>> dd['name']
'dahl'
>>>
71. Map 타입 - Updating Elements
Dictionary 타입에 새로운 key에 할당하면 새로운
것을 추가하고 기존 key로 검색하여 값을 변경하면
기존 값을 변경함
>>> dd = {'name': 'dahl', 'age':50}
>>> dd
{'age': 50, 'name': 'dahl'}
>>> dd['name']
'dahl'
>>>
>>> dd['sex'] ='male'
>>> dd
{'age': 50, 'name': 'dahl', 'sex': 'male'}
>>>
>>> dd['name'] = 'dahl moon'
>>> dd
{'age': 50, 'name': 'dahl moon', 'sex': 'male'}
>>>
새로운 key에 할당: 기
존에 없으므로 추가
기존 key에 할당: 기존
에 있는 값을 변경
72. Map 타입 - Delete Elements
Dictionary 타입에 원소 하나만 삭제, 원소들을
삭제, dictionary instance 삭제
>>> dd
{'age': 50, 'name': 'dahl moon', 'sex': 'male'}
>>> del dd['sex']
>>> dd
{'age': 50, 'name': 'dahl moon'}
>>>
>>> dd.clear()
>>> dd
{}
>>> del dd
>>> dd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dd' is not defined
>>>
기존 원소 하나 삭제
Dict 삭제
모든 원소 삭제
73. Map 타입 -dict class 구조 확인
dict는 하나의 class object로 제공
>>> dict
<type 'dict'>
>>> id(dict)
505532280
>>>
>>> d1 = dict()
>>> id(d1)
105140272
>>> isinstance(d1,dict)
True
>>>
Dict의 인스턴스를 생성하고
isinstance 함수를 이용하여
인스턴스 여부 확인
74. dict 메소드(1)
d= {"k":1,"v":2}
Method example Description
dict.clear() d= {"k":1,"v":2}
d.clear()
d
{}
dict 객체 내의 요소들 클리어
dict.copy() d1 = d.copy()
d1
{'k': 1, 'v': 2}
dict객체를 다른 곳에 deep카피
dict.fromkeys() d2 =d.fromkeys(d)
d2
{'k': None, 'v': None}
dict 객체의 키를 새로운 dict 객체를 생성하는 키로
처리
dict.get(key, default=None) d.get('k')
1
dict내의 키를 가지고 값을 가져옴
dict.has_key(key) d.has_key('k')
True
dict내의 키 존재 여부
dict.items() d.items()
[('k', 1), ('v', 2)]
dict객체의 키와 값을 순서쌍으로 나타내어 리스트
로 전달
75. dict 메소드(2)
d= {"k":1,"v":2}
Method example Description
dict.keys() :d.keys()
['k', 'v']
dict 내의 키를 리스트로 전달
dict.setdefault(key,
default=None)
d.setdefault('s’,3)
d
{'k': 1, 's': 3, 'v': 2}
dict 내의 키와 값을 추가
dict.update(dict2) d.update({1:1})
Id
{1: 1, 'k': 1, 'v': 2}
dict 에 dict을 추가
dict.values() d.values()
[1, 2]
dict 내의 값을 리스틀 전달
dict.pop(‘key’) d
{'k': 1, 's': None, 'v': 2}
d.pop('s')
d
{'k': 1, 'v': 2}
dict 내의 원소를 삭제
76. dict 메소드(3)
d= {"k":1,"v":2}
Method example Description
dict. iteritems() for i in d.iteritems() : print i
('k', 1)
('v', 2)
dict 내의 item을 iterable 객체로 전환
dict. Iterkeys() for i in d.iterkeys() : print i
k
V
dict 내의 key를 iterable 객체로 전환
dict. itervalues() for i in d.itervalues() : print i
1
2
dict 내의 values을 iterable 객체로 전
환
dict.viewitems() d.viewitems()
dict_items([ ('k', 1), ('v', 2)])
dict 내의 item을 보기
dict.viewkeys() d.viewkeys()
dict_keys(['k', 'v'])
dict 내의 키를 보기
dict.viewvalues() d.viewvalues()
dict_values([1, 2])
dict 내의 값을 보기
78. Sequence 타입
다양한 객체의 값을 원소로 값는 데이터 타입
Sequenec Types
String/unicode
Buffer/range
List/tuple
참조 container
참조
참조
값
container
** string 일경우 값만
처리
Elements 관리
79. Map 타입-dictionary
Key/Value로 원소를 관리하는 데이터 타입
요소들은 변경가능하므로 변수에 복사시
참조 container
Name 1 값
Name 2
contain
er
참조
참조
:
:
Dictionary Type
80. 조건제시법/원소나열법
수학 집합을 표시할 때 원소를 나열하는 법과 특정
조건을 함축하여 표시
# 원소나열
S = {1, 2, 4, 8, ..., 2¹²}
# 조건 제시
M = {x | x in S and x even}
82. List Comprehension
리스트 정의시 값을 정하지 않고 호출 시 리스트
내의 값들이 처리되도록 구성
A = [ 표현식 for i in sequence if 논리식]
>>> squares = []
>>> for x in (10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> squares = [x**2 for x in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>
83. Set Comprehension
Set 정의시 값을 정하지 않고 호출 시 Set 내의 값
들이 처리되도록 구성
A = { 표현식 for i in sequence if 논리식}
>>> s = set()
>>> for i in range(10) :
… s.add(i)
>>> s
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> s1 = {x for x in range(9)}
>>> s1
{0, 1, 2, 3, 4, 5, 6, 7, 8}
84. Dict Comprehension
사전 정의시 값을 정하지 않고 호출 시 사전 내의
값들이 처리되도록 구성
A = {표현식 for (k,v) in sequence if 논리식}
>>> d = {}
>>> for (k,v) in zip(range(9),range(9)) :
… d[k] = v
>>> d
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8:
8}
>>> d1 = {x:y for (x,y) in zip(range(9),range(9)) }
>>> d1
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}
>>>
86. Boolean 타입
파이썬은 true/false를 실제 값이 존재하거나 없
는 경우에 조건식을 확정할 경우 사용
값 참 or 거짓
"python" 참
"" 거짓
[1, 2, 3] 참
[] 거짓
() 거짓
{} 거짓
1 참
0 거짓
None 거짓
If 조건식 :
pass
Else :
pass
조건식에 값들이 참과
거짓을 구별하여 처리
87. None
정의된 것이 없는 타입을 세팅할 때 표시
존재하지 않음(Not Exists)
정의되지 않음(Not Assigned, Not Defined)
값이 없음(No Value)
초기값(Initialized Value)