블로그 이미지
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
  • total
  • today
  • yesterday
04-28 18:27
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