블로그 이미지
No pain, no gain!
lepoussin

Tag

Notice

Recent Post

Recent Comment

Recent Trackback

Archive

calendar

1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
  • total
  • today
  • yesterday
02-01 14:34
2007. 2. 24. 20:33 Lecture/열혈강의 Python

1. 튜플의 연산

>>> t = () # 공 튜플
>>> t = (1, 2, 3) # 괄호 사용
>>> t = 1, 2, 3
>>> r = (1,)
>>> r = 1, # 괄호는 없어도 콤마(,)는 무조건 있어야 함
>>> t * 2 # 반복
(1, 2, 3, 1, 2, 3)
>>> t + ('PyKUG', 'user') # 연결
(1, 2, 3, 'PyKUG', 'user')
>>> print t[0], t[1:3] # 인덱싱, 슬라이싱
1 (2, 3)
>>> len(t) # 길이
3
>>> 1 in t # 멤버십 테스트
True
>>> t[10] = 100 # 튜플은 변경 불가능(Imumutable) 자료형

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    t[10] = 100
TypeError: 'tuple' object does not support item assignment

>>> t = (1, 2, 3)
>>> u = t, 4, 5 # 중첩
>>> u
((1, 2, 3), 4, 5)
>>> x, y = 1, 2 # 복수개의 자료 치환
>>> x, y = y, x # swap
>>> x, y
(2, 1)

2. 패킹과 언팩킹

>>> # 튜플
>>> t = 1, 2, 'hello' # 팩킹
>>> x, y, z = t # 언팩킹
>>> # 리스트
>>> a = ['foo', 'bar', 4, 5] # 팩킹
>>> [x, y, z, w] = a # 언팩킹

3. 리스트와의 공통점과 차이점
  1) 공통점
    - 임의의 객체를 저장할 수 있다
    - 시퀀스 자료형(인덱싱, 슬라이싱, 연결, 반복 지원)
  1) 차이점
    - 문자열과 같은 변경 불가능(Immutable) 시퀀스형이다. 따라서 아이템을 변경하려면 슬라이싱과 연결(Concatenation)을 이용해야 한다.
    - 메쏘드를 가지지 않는다.
  3) 상호 변환

>>> 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)

4. 튜플 사용하는 경우
  1) 함수에 있어서 하나 이상의 값을 리턴하는 경우

>>> def calc(a, b):
 return a+b, a-b

>>> x, y = calc(5, 4)

  2) 문자열 포매팅

>>> print 'id : %s, name : %s' % ('creaplz', 'hong')
id : creaplz, name : hong

  3) 튜플에 있는 값들을 함수 인수로 사용할 때(가변 인수)

>>> args = (4, 5)
>>> calc(*args)
(9, -1)

  4) 고정된 값을 표현

>>> d = {'one': 1, 'two': 2}
>>> d.items()
[('two', 2), ('one', 1)]
posted by lepoussin
2007. 2. 24. 14:16 Lecture/열혈강의 Python

1. 리스트의 일반 연산

>>> l = [] # 공 리스트
>>> l = [1, 2, "Great"]
>>> print l[0], l[-1] # 인덱싱
1 Great
>>> print l[1:3], l[:] # 슬라이싱
[2, 'Great'] [1, 2, 'Great']
>>> L = range(10)
>>> L[::2] # 확장 슬라이싱
[0, 2, 4, 6, 8]
>>> l * 2 # 반복
[1, 2, 'Great', 1, 2, 'Great']
>>> l + [3, 4, 5] # 연결
[1, 2, 'Great', 3, 4, 5]
>>> len(l) # 길이
3
>>> 4 in L # 멤버십 테스트
True
>>> l[1] = l[1] + 23 # 변경
>>> l
[1, 25, 'Great']
>>> l[0:2] = [5, 10]  # 교체(슬라이스에서는 양쪽변의 크기가 달라도 됨)
>>> l
[5, 10, 'Great']
>>> l[0:2] = [] # 공 리스트를 이용한 삭제
>>> l
['Great']
>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[0] # del을 이용한 삭제
>>> del a[1:]
>>> a
[1]
>>> a = range(4)
>>> del a[::2]
>>> a
[1, 3]
>>> a = [123, 1234]
>>> a[1:1] = ['spam', 'ham'] # 슬라이스 삽입
>>> a
[123, 'spam', 'ham', 1234]
>>> a[:0] = a # 제일 앞에 추가
>>> a
[123, 'spam', 'ham', 1234, 123, 'spam', 'ham', 1234]
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = range(0, -2, -1) # 교체(확장 슬라이스에서는 양쪽변의 개수가 맞아야 함)
>>> a
[0, 1, -1, 3]
>>> a[::2] = range(3)

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    a[::2] = range(3)
ValueError: attempt to assign sequence of size 3 to extended slice of size 2


2. 중첩 리스트
>>> L = [1, ['a', ['x', 'y'], 'b'], 3]
>>> L[0]
1
>>> L[1]
['a', ['x', 'y'], 'b']
>>> L[1][1]
['x', 'y']
>>> L[1][1][1]
'y'

3. 리스트의 메쏘드들
>>> s = [1, 2, 3]
>>> s.append(5)
# 리스트 마지막에 추가
>>> s
[1, 2, 3, 5]
>>> s.insert(3, 4) # 3 위치에 4 삽입
>>> s
[1, 2, 3, 4, 5]
>>> s.index(3) # 값 3의 위치는?
2
>>> s.count(2)
# 값 2의 개수는?
1
>>> s.reverse()
# 순서 뒤집기(리턴 값 없음)
>>> s
[5, 4, 3, 2, 1]
>>> s.sort()
# 정렬(리턴 값 없음)
>>> s
[1, 2, 3, 4, 5]
>>> s.remove(3)
# 3 삭제(제일 처음 것 1개만 삭제됨)
>>> s
[1, 2, 4, 5]
>>> s.extend([6, 7]) # 리스트를 추가
>>> s
[1, 2, 4, 5, 6, 7]
>>> s.pop()
# 기본적으로 마지막 자료 pop
7
>>> s
[1, 2, 4, 5, 6]
>>> s.pop(0)
# 위치 지정 가능
1
>>> s
[2, 4, 5, 6]


4. 튜플 혹은 리스트의 리스트 반복 참조하기

>>> lt = [('one', 1), ('two', 2), ('three', 3)]
>>> for t in lt:
 print 'name=', t[0], 'num=', t[1]


name= one num= 1
name= two num= 2
name= three num= 3

>>> for t in lt:
 print 'name=%s, num=%s' % t


name=one, num=1
name=two, num=2
name=three, num=3

>>> for name, num in lt:
 print name, num


one 1
two 2
three 3

5. 원하는 순서대로 정렬하기

>>> L = [1, 5, 3, 9, 8, 4, 2]
>>> newList = L.sort() # 리턴되는 값이 없음(자체 변경)
>>> print newList
None
>>> L # 자체 변경됨
[1, 2, 3, 4, 5, 8, 9]
>>> cmp(1, 2)
-1
>>> cmp(5, 2)
1
>>> cmp('abc', 'abc')
0
>>> def mycmp(a1, a2):
 return cmp(a2, a1)

>>> L = [1, 5, 3, 2, 4, 6]
>>> L.sort(mycmp) # 비교 함수 변경
>>> L
[6, 5, 4, 3, 2, 1]
>>> L = [1, 6, 3, 8, 6, 2, 9]
>>> L.sort(reverse=True) # 역순 정렬 지원
>>> L
[9, 8, 6, 6, 3, 2, 1]
>>> L = ['123', '34', '56', '2345']
>>> L.sort()
>>> L
['123', '2345', '34', '56']
>>> L.sort(key=int) # 비교 키를 지원
>>> L
['34', '56', '123', '2345']
>>> # sorted 내장 함수
>>> L = [1, 6, 3, 8, 6, 2, 9]
>>> newList = sorted(L) # L은 변경 내용이 없고, 새로운 리스트가 리턴
>>> newList
[1, 2, 3, 6, 6, 8, 9]
>>> newList = sorted(L, reverse=True)
>>> newList
[9, 8, 6, 6, 3, 2, 1]
>>> L = ['123', '34', '56', '2345']
>>> sorted(L, key=int)
['34', '56', '123', '2345']
>>>
# reversed 내장 함수
>>> newList = reversed(L)
# L은 변경 내용이 없고, 반복자(Iterator)가 리턴
>>> newList
<listreverseiterator object at 0x00DAACF0>
>>> for ele in reversed(L):
 print ele


2345
56
34
123

6. 리스트 내장

>>> # 10보다 작은 정수 중 홀수의 제곱만 리턴하는 예
>>> L = [k * k for k in range(10) if k % 2]
>>> L
[1, 9, 25, 49, 81]
>>> # 2의 배수와 3의 배수 중 두수의 합이 7의 배수가 되는 두 수의 곱의 리스트 만드는 예
>>> [(i, j, i*j) for i in range(2, 100, 2)
 for j in range(3, 100, 3)
 if (i+j) % 7 == 0]
[(2, 12, 24), (2, 33, 66), (2, 54, 108), (2, 75, 150), (2, 96, 192), (4, 3, 12), (4, 24, 96), (4, 45, 180), (4, 66, 264), (4, 87, 348), (6, 15, 90), (6, 36, 216), (6, 57, 342), (6, 78, 468), (6, 99, 594), (8, 6, 48), (8, 27, 216), .. 출력 생략.. , (98, 63, 6174), (98, 84, 8232)]
>>> # 리스트 내장 효과의 발생자
>>> sum(x*x for x in range(10)) # 메모리를 내장하는 새로운 리스트를 생성 안함
285
>>> (x*x for x in range(10)) # 발생자(Generator) 생성
<generator object at 0x00DC3D78>
>>> sum([x*x for x in range(10)]) # 새로운 리스트를 생성하여 sum 연산
285

7. 순환 참조 리스트

>>> GNU = ['is not Unix']
>>> GNU.insert(0, GNU)
>>> GNU

[[...], 'is not Unix']
>>> GNU[0]
[[...], 'is not Unix']
>>> GNU[0][0]
[[...], 'is not Unix']
>>> GNU[0][0][0]
[[...], 'is not Unix']

8. 순차적인 정수 리스트 만들기

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 15)
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> range(5, 15, 2)
[5, 7, 9, 11, 13]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
 
>>> sun, mon, tue, wed, thu, fri, sat = range(7)

9. 배열 표현

>>> mat = [[0] * 4] * 3
>>> mat
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> mat[0][0] = 100
>>> mat
[[100, 0, 0, 0], [100, 0, 0, 0], [100, 0, 0, 0]]
>>> mat = [[0]*4 for x in range(3)]
>>> mat
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> mat[0][0] = 100
>>> mat
[[100, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

※ arrary,  NumPy 모듈 사용하여 고수준의 행렬 표현 및 연산 가능
 

posted by lepoussin
2007. 2. 21. 02:00 Lecture/열혈강의 Python

1. 시퀀스 자료형 : 문자열, 리스트, 튜플
  1) 인덱싱(indexing) : [k]

>>> s = 'abcdef' # 문자열
>>> l = [100, 200, 300] # 리스트
>>> s[0]  # 참조
'a'
>>> s[1]
'b'
>>> s[-1]
'f'
>>> l[1]
200
>>> l[1] = 900 # 치환

  2) 슬라이싱(Slicing) : [s:t]

>>> s = 'abcdef'
>>> l = [100, 200, 300]
>>> s[1:3] # 1번 위치와 3번 위치 사이를 나타냄
'bc'
>>> s[1:] # 1부터 끝까지
'bcdef'
>>> s[:] # 처음부터 끝까지
'abcdef'
>>> s[-100:100] # 범위를 넘어서면 범위 내의 값으로 자동 처리
'abcdef'
>>> l[:-1] # 맨 오른쪽 값을 제외하고 모두
[100, 200]
>>> s[::2] # 2칸 단위로
'ace'
>>> s[::-1] # 거꾸로
'fedcba'

  3) 연결하기(Concatenation) : +

>>> s = 'abc' + 'def'
>>> s
'abcdef'
>>> L = [1, 2, 3] + [4, 5, 6]
>>> L

[1, 2, 3, 4, 5, 6]

  4) 반복하기(Repetition) : *

>>> s = 'Abc'
>>> s * 4
'AbcAbcAbcAbc'
>>> L = [1, 2, 3]
>>> L * 2
[1, 2, 3, 1, 2, 3]

  5) 멤버십 테스트(Membership Test) : in

>>> t = (1, 2, 3, 4, 5)
>>> 2 in t
True
>>> 10 not in t
True
>>> 'ab' in 'abcd' # 문자열인 경우 부분 문자열 확인 가능
True

  6) 길이 정보 : len

>>> l = [1, 2, 3]
>>> len(l)

3

2. 문자열 정의
  1) 한 줄 문자열 : ' or "
  2) 여러 줄 문자열 : ''' or """
  3) 이스케이프 문자

Escape Sequence Meaning
\newline Ignored
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\N{name} Character named name in the Unicode database (Unicode only)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\uxxxx Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo
\xhh Character with hex value hh

  4) 문자열 연산(시퀀스 자료형의 특징 참조)

>>> str1 = 'Firtst String'
>>> str1[0] = 'f' # 변경 불가능(Immutable) 자료형이므로 에러 발생


Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    str1[0] = 'f'
TypeError: 'str' object does not support item assignment

3. 문자열 변경

>>> s = 'spam and egg'
>>> s = s[:5] + 'cheese' + s[5:]
>>> s
'spam cheeseand egg'

4. 문자열 포매팅(Formatting) : %s, %r, %c, %d, %i, %u, %o, %x, %X, %e, %E, %f, %g, %G

>>> format = 'name = %s, age = %s'
>>> format % ('gslee', 24)
'name = gslee, age = 24'
>>> "%s -- %s -- %d -- %f -- %e" % ((1, 2), [3, 4, 5], 5, 5.3, 101.3)
'(1, 2) -- [3, 4, 5] -- 5 -- 5.300000 -- 1.013000e+002'
>>> print '%(이름)s -- %(전화번호)s' % {'이름': '이강성', '전화번호': 5284}
이강성 -- 5284

5. 문자열 메쏘드

>>> # 대ㆍ소문자로 변환 관련 메쏘드
>>> s = 'i like programming.'
>>> s.upper()
'I LIKE PROGRAMMING.'
>>> s.upper().lower()
'i like programming.'
>>> 'I Like Programming'.swapcase()
'i lIKE pROGRAMMING'
>>> s.capitalize()
'I like programming.'
>>> s.title()
'I Like Programming.'
>>> # 검색 관련 메쏘드
>>> s = 'i like programming, i like swimming.'
>>> s.count('like') # 문자열 s에서 'like'라는 부분문자열이 발생한 횟수를 리턴
2
>>> s.find('like') # 'like'의 offset를 리턴(검색)
2
>>> s.find('my') # 찾는 문자열이 없을 경우 -1 리턴
-1
>>> s.rfind('like') # find와 같지만 문자열 s의 뒤쪽부터 탐색
22
>>> s.index('like')
2
>>> s.index('my') # find와 같지만 찾는 문자열이 없을 경우 예외 발생

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    s.index('my')
ValueError: substring not found

>>> s.rindex('like') # index와 같지만 문자열 s의 뒤쪽부터 탐색
22
>>> s.startswith('i like') # i like로 시작하는 문자열인가?
True
>>> s.endswith('swimming.') # swimming.으로 끝나는 문자열인가?
True
>>> s.startswith('progr', 7) # 7번째 문자열이 progr로 시작하는가?
True
>>> s.endswith('like', 0, 26) # 0부터 26번째 위치 사이의 문자열이 like로 끝나는가?
True
>>> # 편집 및 치환 관련 메쏘드
>>> u = ' spam and ham '
>>> u.strip() # 좌우 공백 제거
'spam and ham'
>>> u.rstrip() # 오른쪽 공백 제거
' spam and ham'
>>> u.lstrip() # 왼쪽 공백 제거
'spam and ham '
>>> '   abd   '.strip()
'abd'
>>> '><>abc<><><>'.strip('<>')
'abc'
>>> '><><abc<><><>\n'.strip('<>')
'abc<><><>\n'
>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
u'\u4001abc'
>>> u.replace('spam', 'spam, egg') # 'spam'을 'spam, egg'로 변경
' spam, egg and ham '
>>> # 문자열 분리와 결합 관련 메쏘드
>>> u = '  spam and ham    '
>>> u.split() # 공백으로 분리
['spam', 'and', 'ham']
>>> u.split('and') # 'and로 분리
['  spam ', ' ham    ']
>>> t = u.split()
>>> ':'.join(t) # ':' 문자로 결합
'spam:and:ham'
>>> print '\n'.join(t) # 줄 바꾸기로 결합
spam
and
ham

>>> lines = '''first line
second line
third line'''
>>> lines.splitlines() # 라인 단위로 분리
['first line', 'second line', 'third line']
>>> s = 'one:two:three:four'
>>> s.split(':', 2) # 두 번만 분리
['one', 'two', 'three:four']
>>> s.rsplit(':', 1) # 오른쪽부터 처리
['one:two:three', 'four']
>>> # 정렬 관련 메쏘드
>>> u = 'spam and egg'
>>> u.center(60) # 전체 60문자의 가운데에 맞춤
'                        spam and egg                        '
>>> u.ljust(60) # 왼쪽에 맞춤
'spam and egg                                                '
>>> u.rjust(60) # 오른쪽에 맞춤
'                                                spam and egg'
>>> u.center(60, '-') # 공백 대신 '-' 문자로 채움
'------------------------spam and egg------------------------'
>>> '1\tand\t2'.expandtabs() # 탭(\t)을 8자 공백으로 사용
'1       and     2'
>>> '1\tand\t2'.expandtabs(4)
'1   and 2'
>>> # 구성된 문자열의 특성 유무 파악 관련 메쏘드
>>> '1234'.isdigit()
True
>>> 'abcd'.isalpha()
True
>>> '1abc234'.isalnum()
True
>>> 'abc'.islower() # 소문자인가?
True
>>> 'ABC'.isupper()
True
>>> ' \t\r\n'.isspace() # 공백문자인가?
True
>>> 'This Is A Title'.istitle() # 제목 문자열인가?
True
>>> # 채우기 및 자리 맞추기 관련 메쏘드
>>> s = '123'
>>> s.zfill(5)
'00123'
>>> 'goofy'.zfill(6) # 빈 자리는 0으로 채워짐
'0goofy'

6.. string 모듈

>>> import string
>>> d = string.letters + string.digits
>>> d
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
>>> userid = raw_input('your id : ')
your id : creaplz510
>>> for ch in userid:
 if ch not in d:
  print 'invalid user id'
  break

7. 유니 코드

>>> unicode('한글', 'cp949') # 인코딩을 명시적으로 알려주어야 함
u'\ud55c\uae00'
>>> unicode('한글', 'cp949').encode('utf-8') # 'utf-8' 코드로 변환
'\xed\x95\x9c\xea\xb8\x80'
>>> len('한글과 세종대왕')
15
>>> len(unicode('한글과 세종대왕', 'mbcs'))
8
>>> u = unicode('한글과 세종대왕', 'mbcs')
>>> print u[0]

>>> print u[1]

>>> ord('A') # 문자 'A'의 ASCII 코드값
65
>>> chr(65) # 코드 65에 해당하는 문자
'A'
>>> ord(unicode('가', 'cp949'))
44032
>>> hex(ord(unicode('가', 'cp949')))
'0xac00'
>>> print unichr(0xac00)

>>> print unichr(0xd7a3)

8. 문서 문자열 : 도움말 사용
# file : docstring.py
'''
Module __doc__ string
line1
line2
'''
class Ham:
    "Ham class __doc__ string"
    def func(self):
        "Ham class func __doc__ string"
        pass

>>> import docstring
>>> print docstring.__doc__
Module __doc__ string
line1
line2
>>> print docstring.Ham.__doc__
Ham class __doc__ string
>>> print docstring.Ham.func.__doc__
Ham class func __doc__ string

posted by lepoussin