블로그 이미지
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 29 30
31
  • total
  • today
  • yesterday
03-29 06:57
2007. 3. 8. 07:58 Lecture/열혈강의 Python
1. 파일쓰기
  - open(file) 내장 함수로 파일 객체를 얻음
  - 얻어진 파일 객체서 자료를 읽고 씀
  - close로 객체 사용을 종료(생략 가능)
>>> s = '''
Its power: Python developers typically report
they are able to develop application in a half
to a tenth the amount of time it takes them to do
the same work in such langueges as C.
'''
>>> f = file('t.txt', 'w')
>>> f.write(s)
>>> f.close()


2. 파일 읽기

>>> f = file('t.txt') # 두 번째 인수 생략 시, 읽기 모드로 동작
>>> s = f.read()
>>> print s

Its power: Python developers typically report
they are able to develop application in a half
to a tenth the amount of time it takes them to do
the same work in such langueges as C.

3. 라인 단위로 파일 읽기
  - 파일 객체의 반복자(Iterator) 이용하기(가장 효과적인 방법)

>>> f = open('t.txt')
>>> for line in f:
 print line,

  - readline : 한 번에 한 줄씩 읽는다.

>>> f = open('t.txt')
>>> line = f.readline()
>>> while line:
 print line, # line 자체에 \n이 포함되어 있어 콤마(,)를 사용
 line = f.readline()

  - readlines : 파일 전체를 라인 단위로 끊어서 리스트에 저장한다.

>>> f = open('t.txt')
>>> for line in f.readlines():
 print line,

  - xreadlines : readlines와 유사하지만 파일 전체를 한꺼번에 읽지는 않고, 필요할 때만 읽어서 공급한다. 큰 파일을 for 문으로 라인 단위로 읽을 때 편리하다.

>>> f = open('t.txt')
>>> for line in f.xreadlines():
 print line,

4. 라인 단위로 파일 쓰기

>>> lines = ['first line\n', 'second line\n', 'third line\n']
>>> f = open('t1.txt', 'w')
>>> f.writelines(lines)
>>>
>>> lines = ['first line', 'second line', 'third line']
>>> f = open('t1.txt', 'w')
>>> f.write('\n'.join(lines))

※ 단어의 수 구하기

>>> n = len(open('t.txt').read().split())
>>> print n
35

※ 라인의 수 구하기

>>> len(open('t.txt').readlines())
5
>>> open('t.txt').read().count('\n')
5

※ 문자의 수 구하기

>>> f = open('t.txt')
>>> len(f.read()) # 줄바꾸기 : '\012'
182
>>> os.path.getsize('t.txt') # 줄바꾸기 : '\015\012'
187L

5. 파일에서 원하는 만큼의 문자 읽기

>>> f = open('t.txt')
>>> f.read(10) # 10바이트 만큼만 읽기
'\nIts power'
>>> f.read(10)
': Python d'

6. 파일 처리 모드
  - 'r' : 읽기 전용
  - 'w' : 쓰기 전용
  - 'a' : 파일 끝에 추가(쓰기 전용)
  - 'r+' : 읽고 쓰기
  - 'w+' : 읽고 쓰기(기존 파일 삭제)
  - 'a+' : 파일 끝에 추가(읽기도 가능)
  - 'rb' : 이진 파일 읽기 전용
  - 'wb' : 이진 파일 쓰기 전용
  - 'ab' : 이진 파일 끝에 추가(쓰기 전용)
  - 'rb+' : 이진 파일 읽고 쓰기
  - 'wb+' : 이진 파일 읽고 쓰기(기존 파일 삭제)
  - 'ab+' : 이진 파일 끝에 추가(읽기도 가능)
※ 플랫폼에 의존하지 않는 코드를 작성하려 한다면 이진 파일을 다룰 때 b 플래그를 사용하는 것이 좋다.

7. 임의 접근 파일
  - seek(n) : 파일의 n번째 바이트로 이동
  - seek(n, 1) : 현재 위치에서 n바이트 이동(n이 양수이면 뒤쪽으로, 음수이면 앞쪽으로 이동)
  - seek(n, 2) : 맨 마지막에서 n바이트 이동(n은 보통 음수)
  - tell() : 현재의 파일 포인터 위치를 돌려줌

>>> fn = 't.txt'
>>> f = open(fn, 'w+')
>>> s = '0123456789abcdef'
>>> f.write(s)
>>> f.seek(5)
>>> print f.tell() # 현재 위치를 돌려줌
5
>>> print f.read(1) # 1바이트 읽기
5
>>> f.seek(-3, 2) # 끝부터 앞으로 3번째 지점
>>> print f.tell()
13
>>> print f.read(1)
d

8. 파일 객체 속성들
  1) 기본 파일 메쏘드
    - file.close() : 파일을 닫는다. 더 이상 입ㆍ출력할 수 없게 된다.
    - file.read([size]) : 원하는 바이트 수만큼 파일에서 읽어 온다. 인수를 지정하지 않으면 전체 파일을 읽어 온다.
    - file.readline([size]) : 라인 하나를 읽어 들인다. size가 지정되면 읽을 수 있는 최대 바이트 수가 된다.
    - file.readlines() : 전체 라인을 readline()을 이용하여 읽어 들인 라인을 리스트에 넣어서 리턴한다.
    - file.write(str) : 문자열 str을 파일에 쓴다.
    - file.writelines(list) : 문자열 리스트를 파일에 쓴다. 줄바꾸기가 자동으로 삽입되지는 않는다.
    - file.seek(offset[, whence]) : whence의 기본 값은 0이다. 0이면 시작 기준, 1이면 현재 위치 기준, 2이면 끝 기준에서 offset만큼 떨어진 위치에 파일 포인터를 위치시킨다.
    - file.tell() : 파일의 현재 위치를 리턴한다.
  2) 기타의 파일 메쏘드
    - file.flush() : 버퍼가 다 채워지지 않았어도 내부 버퍼의 내용을 파일에 보낸다.
    - file.fileno() : file 객체의 파일 기술자(File Descriptor)(정수)를 리턴한다.
    - file.isatty() : 만일 file 객체가 tty와 같은 장치이면 1이면 0을 리턴
    - file.truncate([size]) : 파일 크기를 지정된 크기로 잘라 버림. 인수를 주지 않으면 현재 위치에서 자른다.
  3) 파일 객체 속성
    - file.closed : file이 close 되었으면 1 아니면 0
    - file.mode : 파일이 오픈된 모드
    - file.name : open()할 때 사용된 파일 이름
    - file.softspace : 1이면 print문을 사용할 때 값 출력 사이에 자동적으로 스페이스가 출력됨. 0이면 스페이스가 자동으로 삽입되지 않음

9. 파일 입ㆍ출력 예제

## 지정한 파일의 특정 문자열을 다른 문자열로 변환
# @file repalce.py

import sys  # argv를 위해서 사용
import re   # 정규식 처리 모듈, subn을 위해서 사용

def replace(fName, srcStr, desStr):
    f = open(fName)
    txt = f.read()
    txt = re.subn(srcStr, desStr, txt)[0]
    return txt

if __name__ == '__main__':
    if len(sys.argv) != 4:
        print '''Usage : replace fileName srcStr desStr'''
        sys.exit()
    print replace(sys.argv[1], sys.argv[2], sys.argv[3])


10. 표준 입ㆍ출력 방향 전환
  1) 표준 출력을 파일로 저장하기
    - 출력 방향 전환하기

import sys

f = open('t.txt', 'w')
stdout = sys.stdout # 표준 출력 파일 저장해 두기
sys.stdout = f  # 파일 객체로 변경
print 'Sample output'
print 'Good'
print 'Good'
f.close()
sys.stdout = stdout # 필요하면 복구

    - print 문을 직접 이용하기

>>> import sys
>>> print >> sys.stderr, 'Warning: action filed not supplied'
Warning: action filed not supplied
>>> f = open('t.txt', 'w')
>>> print >> f, 'spam string'
>>> f.close()


  2) 표준 출력을 문자열로 저장하기

import sys
import StringIO

stdout = sys.stdout # 표준 출력 파일 저장해 두기
sys.stdout = f = StringIO.StringIO()    # 출력 파일 방향 전환

print 'Sample output'
print 'Good'
print 'Good'

sys.stdout = stdout # 표준 출력 복구
s = f.getvalue()    # 내부 문자열 가져오기

print 'Done-----'
print s

  3) 문자열을 파일 객체처럼 읽어 내기

try:
    import cStringIO    # 빠른 처리를 원한다면 C 버전 모듈인 cStringIO 사용
    StringIO = cStringIO
except:
    import StringIO
s = '''
Python is a cool little language.
It is wall designed, compact, easy to learn and fun to program in.
'''
f = StringIO.StringIO(s)    # 문자열 객체에서 파일 객체 얻어내기
print f.read().upper()  # 대문자로 변환


11. 지속 모듈 : 프로그램이 종료되고 나서도 존재하게 하고, 그 후에 다시 그 데이터를 프로그램에서 사용
  1) 종류
    - DBM 관련 모듈
    - pickle 모듈
    - marshal 모듈
    - shelve 모듈
  2) DBM 파일 관련 모듈 사용하기
    - anydbm, dbm, gdbm, dbhash, dumbdbm 등
    - anydbm 모듈 : 사용 가능한 DBM 호환 가능 최적의 모듈을 찾아 준다.
    - 키에 의한 참조(인덱싱)로 파일에서 자료를 읽어 오고, 인덱싱으로 치환하는 것으로 파일에 자료를 저장
    - 키와 값은 반드시 문자열이어야 한다.

>>> import anydbm
>>> f = anydbm.open('music', 'c') # 'c'(create)는 파일이 없으면 생성, 있으면 읽기로 오픈
>>> f['flute'] = 'wood wind' # 인덱싱으로 치환
>>> f['violin'] = 'string'
>>> f['piano'] = 'keyboard'
>>> f.keys() # keys() 메쏘드
['flute', 'violin', 'piano']
>>> f.values()
['wood wind', 'string', 'keyboard']
>>> f.items()
[('flute', 'wood wind'), ('violin', 'string'), ('piano', 'keyboard')]
>>> len(f) # 레코드 수
3
>>> 'oboe' in f # 멤버십 테스트
False
>>> f['flute'] # 인덱싱으로 값 읽어 오기
'wood wind'
>>> f['violin']
'string'
>>> f.close() # 파일 닫기
>>> ========================== RESTART ==========================
>>> import anydbm
>>> f = anydbm.open('music', 'c') # 'music' 파일 열기
>>> f.keys() # 키 목록 얻기
['flute', 'violin', 'piano']
>>> for k in f: # 전체 내용 출력
 print k, f[k]

flute wood wind
violin string
piano keyboard

>>> f['oboe'] = 'wood wind' # 내용 추가
>>> f['piano'] = 'keyboard instrument' # 내용 변경
>>> del f['violin'] # 내용 삭제
>>> for k in f: # 다시 전체 내용 출력
 print k, f[k]

flute wood wind
piano keyboard instrument
oboe wood wind


  3) 피클링
    - 모든 객체 저장
    - 재귀적 관계도 모두 처리
    - import pickle(또는 cPickle) : 모듈 import
      pickle.dump(출력할 객체, 파일 객체) : 파일로 객체 출력
      object = pickle.load(파일 객체) : 파일에서 객체를 읽어들임
      s = pickle.dumps(출력할 객체) : 문자열로 객체 출력
      object = pickle.loads(s) : 문자열에서 객체를 읽어들임
    - 장점 : 디버깅을 쉽게하고 문제가 생겼을 때 일반 텍스트 에디터로 복구를 쉽게할 수 있다.
    - 단점 : 파일 크기도 크고 또한 처리 속도도 느리다.
    ※ cPickle 모듈은 pickle 모듈과 같은 인터페이스를 가지고 있지만 약 1000배 빨리 수행되도록 설계되었다.

## pickle sample

# @file pickleSample1.py
try:
    import cPickle
    pickle = cPickle
except:
    import pickle

phone = {'tom': 4358382, 'jack': 9465215, 'jim': 6851325, 'Joseph': 6584321}
List = ['string', 1234, 0.2345]
Tuple = (phone, List)   # 리스트, 튜플, 사전의 복합 객체

f = open('t2.txt', 'w') # 파일 객체를 얻는다.

pickle.dump(Tuple, f)   # 파일로 복합 객체 출력(pickling)
f.close()

f = open('t2.txt')

x, y = pickle.load(f)   # 파일에서 읽어 오기(unpickling)
print x # x는 사전
print y # y는 리스트


# @file pickleSample2.py
try:
    import cPickle
    pickle = cPickle
except:
    import pickle
class Simple:   # 가장 단순한 클래스를 정의
    pass

s = Simple()    # 인스턴스 객체 생성
s.count = 10    # 인스턴스 이름 공간에 변수 생성

f = open('t3.txt', 'w') # 인스턴스 저장
pickle.dump(s, f, 1)    # bin=1 : 이진 모드로 저장
f.close()

f = open('t3.txt')
t = pickle.load(f)  # 인스턴스 가져오기

print t.count




 

posted by lepoussin
2007. 3. 3. 00:49 Lecture/열혈강의 Python
1. 객체의 복사 : 같은 값을 가지는 객체를 하나 혹은 그 이상 만드는 것
  1) copy 모듈을 이용한 객체 복사
    - 얕은 복사(Shallow Copy) : 복합 객체를 별도로 생성하되 내용은 원래의 레퍼런스로 채운다.
>>> import copy
>>> a = [1, 2, 3]
>>> b = [4, 5, a]
>>> x = [a, b, 100]
>>> y = copy.copy(x)

    - 깊은 복사(Deep Copy) : 복합 객체를 생성하고 내용을 재귀적(Recursive)으로 복사한다.
>>> import copy
>>> a = [1, 2, 3]
>>> b = [4, 5, a]
>>> x = [a, b, 100]
>>> y = copy.deepcopy(x)


2. 형 변환
  1) 수치 형 변환
    - 정수형 변환 : int()
      ※ 실수→정수 : int(), round(), floor(), ceil()
    - 실수, 롱형으로의 형 변환 : float(), long()
    - 복소수로의 형 변환 : complex()
  2) 시퀀스 자료형 변환
    - 리스트로 변환 : list()
    - 튜플로 변환 : tuple()

>>> t = (1, 2, 3, 4)
>>> l = [5, 6, 7, 8]
>>> s = 'abcd'
>>>
>>> print list(t), list(s)
[1, 2, 3, 4] ['a', 'b', 'c', 'd']
>>> print tuple(l), tuple(s)
(5, 6, 7, 8) ('a', 'b', 'c', 'd')

  3) 문자열로의 형 변환
    - 비형식적인 문자열로 변환 : str()
    - 형식적인 문자열로 변환 : repr()
    - `obj` : repr(obj)와 동일
    ※ 객체 ↔ 문자열 : repr(str은 완벽한 변환 안됨), eval 사용

>>> L = ['파란 하늘', 'blue sky', 1, 1234L, 1/3.0]
>>> for s in L:
 print 's', s
 print 'str(s)', str(s)
 print 'repr(s)', repr(s)
 print '\'s\'', `s`
 print


s 파란 하늘
str(s) 파란 하늘
repr(s) '\xc6\xc4\xb6\xf5 \xc7\xcf\xb4\xc3'
's' '\xc6\xc4\xb6\xf5 \xc7\xcf\xb4\xc3'

s blue sky
str(s) blue sky
repr(s) 'blue sky'
's' 'blue sky'

s 1
str(s) 1
repr(s) 1
's' 1

s 1234
str(s) 1234
repr(s) 1234L
's' 1234L

s 0.333333333333
str(s) 0.333333333333
repr(s) 0.33333333333333331
's' 0.33333333333333331

  4) 문자열 요소를 가지는 리스트나 튜플을 문자열로 변환

>>> import string
>>> s = 'Python is the first language'
>>> L = s.split()
>>> L
['Python', 'is', 'the', 'first', 'language']
>>> ' '.join(L)
'Python is the first language'
  5) 리스트, 튜플과 사전의 변환
    - 사전에서 리스트로 변환
>>> d = {1: 'one', 2: 'two', 3: 'three'}
>>> d.keys()
[1, 2, 3]
>>> d.values()
['one', 'two', 'three']
>>> d.items()
[(1, 'one'), (2, 'two'), (3, 'three')]
    - 리스트에서 사전으로 변환
>>> keys = ['a', 'b', 'c', 'd']
>>> values = [1, 2, 3, 4]
>>> L = zip(keys, values)
>>> L
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> dict(L)
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

  6) 문자 변환
>>> chr(97) # 아스키 코드 → 문자
'a'
>>> ord('a') # 문자 → 아스키 코드
97
  7) 임의의 진수를 10진수로 변환
>>> int('64', 16) # 16진수 '64'를 10진수로
100
>>> int('144', 8) # 8진수 '144'를 10진수로
100
>>> int('101111', 2) # 2진수 '101111'을 10진수로
47
>>> int('14', 5) # 5진수 '14'를 10진수로
9
  8) 10진수를 임의의 진수로 변환
    - 10진수에서 8, 16진수로
>>> hex(100) # 10진수 100을 16진수 문자열로 변환
'0x64'
>>> oct(100) # 10진수 100을 8진수 문자열로 변환
'0144'

    - 10 진수에서 2진수로

## 10진수 → 2진수

# @file int2bin1.py
octtab = {'0': '000', '1': '001', '2': '010', '3': '011',
    '4': '100', '5': '101', '6': '110', '7': '111'}

def bin1(d, width=0):
    "integer to binary(string)"
    s = "%o" % d
    b = ''
    for el in s:
        b += octtab[el]
    if width > 0:
        if len(s) > width:
            return b[:width]
        b = b.zfill(width)
    return b

print bin1(23, 7)   # 0010111

# @file int2bin2.py
def bin2(n, width=0):
    result = []
    while 1:
        result[:0] = [str(n&1)]
        n >>= 1
        if not n:
            break
    results = ''.join(result)
    if not width:
        width = len(results)
    return results.zfill(width)[:width]

print bin2(23, 7)
# 0010111

    - 10진수에서 임의의 진수로

## 10진수 → 임의의 진수
#  @param n 10진수
#  @param base 변환할 진수
#  @param width 출력 문자열 폭. 0이면 기본 값

def int2digit(n, base, width=0):
    res = ''
    while n > 0:
        n, r = divmod(n, base)
        if r > 9:
            r = chr(ord('a')+r-10)
        res += str(r)
    if not res:
        res = '0'
    if not width:
        width = len(res)
    return res.zfill(width)[:width]

print int2digit(70, 5)       # 240
print int2digit(70, 12)     # 5a
print int2digit(70, 15)     # 4a
print int2digit(70, 16)     # 46
print int2digit(70, 2, 8)   # 01000110

  9) 정수를 콤마가 있는 문자열로 변환

>>> import locale
>>> locale.setlocale(locale.LC_ALL, "") # 사용자 기본 환경(국가 혹은 언어)으로 설정
'Korean_Korea.949'
>>> print locale.format("%d", 10030405, 1)
10,030,405
posted by lepoussin
2007. 2. 24. 22:55 Lecture/열혈강의 Python

1. 사전 객체의 기초 연산
  - 내부적으로 해쉬(Hash)라는 기법을 이용하여 자료 저장
  - 자료의 순서를 가지지 않는다.
  - 값은 임의의 객체가 될 수 있지만, 키는 변경 불가능(Immutable) 자료형이어야 한다.
  - 문자열, 숫자, 튜플은 키가 될 수 있지만 리스트, 사전은 키가 될 수 없다.

>>> member = {'basketball': 5, 'soccer':11, 'baseball':9}
>>> member['baseball'] # 검색
9
>>> member['volleyball'] = 7 # 새 값 설정
>>> member
{'soccer': 11, 'basketball': 5, 'baseball': 9, 'volleyball': 7}
>>> member['volleyball'] = 10 # 변경
>>> member
{'soccer': 11, 'basketball': 5, 'baseball': 9, 'volleyball': 10}
>>> len(member) # 길이
4
>>> del member['baseball'] # 항목 삭제
>>> 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

※ 다양한 방법으로 사전 객체 생성하기

>>> dict() # 빈 사전 생성
{}
>>> dict(one=1, two=2) # 키워드 인수를 지정하여 사전 생성
{'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2)]) # (key, value) 쌍의 시퀀스로부터 사전 생성
{'two': 2, 'one': 1}
>>> dict({'one':1, 'two':2}) # 사전 객체를 인수로 받아 새로운 사전 생성
{'two': 2, 'one': 1}
>>> keys = ['one', 'two', 'three']
>>> values = (1, 2, 3)
>>> zip(keys, values) # zip은 자료를 순서대로 묶어줌
[('one', 1), ('two', 2), ('three', 3)]
>>> dict(zip(keys, values))
{'three': 3, 'two': 2, 'one': 1}

2. 사전 객체의 메쏘드

>>> phone = {'jack': 9465215, 'jim': 1111, 'Joseph': 6584321}
>>> phone.keys() # 키의 리스트를 반환
['jim', 'Joseph', 'jack']
>>> phone.values() # 값의 리스트를 반환
[1111, 6584321, 9465215]
>>> phone.items() # (키, 값)의 리스트를 반환
[('jim', 1111), ('Joseph', 6584321), ('jack', 9465215)]
>>> 'jack' in phone # 'jack'이 phone의 키에 포함되어 있는가?
True
>>> 'lee'in phone
False
>>> p = phone # 사전 레퍼런스 복사(사전 객체는 공유됨)
>>> phone['jack'] = 1234 # 변경
>>> phone
{'jim': 1111, 'Joseph': 6584321, 'jack': 1234}
>>> p # phone과 동일하게 변경됨
{'jim': 1111, 'Joseph': 6584321, 'jack': 1234}
>>> ph = phone.copy() # 사전 복사(별도의 사전 객체를 리턴)
>>> phone['jack'] = 1111 # 변경
>>> ph # phone과 다른 객체이기 때문에 변경 안되었음
{'jim': 1111, 'Joseph': 6584321, 'jack': 1234}
>>> ph.get('jack') # 'jack'키에 대한 값을 얻음
1234
>>> ph.get('creaplz') # 값이 없는 경우 None을 리턴
>>> ph['creaplz'] # ph['creaplz']는 값이 없는 경우 예외를 발생 

Traceback (most recent call last):
  File "<pyshell#98>", line 1, in <module>
    ph['creaplz']
KeyError: 'creaplz'

>>> ph.get('creaplz', 510) # 인수를 하나 더 써주면, 존재하지 않는 키인데도 지정한 인수를 리턴
510
>>> ph # 사전에는 변화 없음
{'jim': 1111, 'Joseph': 6584321, 'jack': 1234}
>>> ph.setdefault('creaplz', 510) # 'creaplz'의 값을 꺼내되, 없으면 510로 설정
510
>>> ph # 'creaplz': 510이 설정
{'jim': 1111, 'Joseph': 6584321, 'jack': 1234, 'creaplz': 510}
>>> ph.popitem() # 한 아이템을 꺼냄
('jim', 1111)
>>> ph.popitem() # 또 한 아이템을 꺼냄
('Joseph', 6584321)
>>> ph # popitem 결과
{'jack': 1234, 'creaplz': 510}
>>> ph.pop('jack') # 지정한 키를 pop
1234
>>> ph
{'creaplz': 510}
>>> phone.update(ph) # 사전 phone의 내용을 ph으로 추가 갱신
>>> phone
{'jim': 1111, 'Joseph': 6584321, 'jack': 1234, 'creaplz': 510}
>>> phone.clear() # 사전의 모든 입력을 제거
>>> phone
{}

3. 심볼 테이블

>>> a = 1
>>> b = 100
>>> name = 'creaplz'
>>> dic = {'Python': 'Good', 'Perl': 'Not Good'}
>>> globals() # 전역 영역(모듈 영역)의 심볼 테이블(사전) 얻음
{'a': 1, 'b': 100, 'name': 'creaplz', '__builtins__': <module '__builtin__' (built-in)>, 'dic': {'Python': 'Good', 'Perl': 'Not Good'}, '__name__': '__main__', '__doc__': None}
>>> locals() # 지역 영역의 심볼 테이블 얻음(대화형 최상위 모드에서는 globals()와 별 차이가 없음)
{'a': 1, 'b': 100, 'name': 'creaplz', '__builtins__': <module '__builtin__' (built-in)>, 'dic': {'Python': 'Good', 'Perl': 'Not Good'}, '__name__': '__main__', '__doc__': None}
>>> # 객체의 심볼 테이블
>>> class C:
 x = 10
 y = 20

>>> C.__dict__ # 클래스의 심볼 테이블 얻음
{'y': 20, 'x': 10, '__module__': '__main__', '__doc__': None}
>>> c = C() # 객체 생성
>>> c.a = 100
>>> c.b = 200
>>> c.__dict__ # 클래스 인스턴스의 심볼 테이블 얻음
{'a': 100, 'b': 200}
>>> def f():
 pass
>>> f.a = 1
>>> f.b = 2
>>> f.__dict__ # 함수의 심볼 테이블 얻음
{'a': 1, 'b': 2}


4. 사전을 for문으로 참조하기

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

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

>>> # 정렬된 결과를 한번만 이용하기
>>> for key, value in sorted(d.items()): # 순서 정렬(키 기준)
 print key, value


one 1
three 3
two 2

>>> for key, value in sorted(d.items(), key=lambda item:item[1]): # 순서 정렬(값 기준)
 print key, value


one 1
two 2
three 3

posted by lepoussin
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