Fluent Python Ch02

( 출처 : 전문가를 위한 파이썬 / Fluent Python )


[ An Array of Sequences ]

1. Overview of Built-In Sequences

2 종류의 sequence

  • 1) CONTAINER sequence
    • 서로 다른 형태의 data 담을 수 있음
    • ex) list, tuple, collections.deque
  • 2) FLAT sequence
    • 하나의 형태의 data만을 담을 수 있음
    • ex) str, bytes, bytearray, memoryview, array.array


( Mutability (가변성) 에 따라서도 구분 가능 )

2종류의 sequence

  • 1) MUTABLE sequences
    • 원소 바꿀수 O
    • ex) list, bytearary, array.array, collections.deque
  • 2) IMMUTABLE sequences
    • 원소 바꿀수 X
    • ex) tuple, str, bytes


2. List Comprehension

사용 X

>>> symbols = '$¢£¥€¤'
>>> codes = []
>>> for symbol in symbols:
... codes.append(ord(symbol))


사용 O

>>> symbols = '$¢£¥€¤'
>>> codes = [ord(symbol) for symbol in symbols]


그렇다고 for loop이 무의미한거? NO!

단지 “새로운 리스트 생성”에 있어서, list comprehension > for loop 이라는 뜻!


3. List Comprehension vs map/filter

map&filter 사용 대신, list comprehension쓰자!

사용 X

>>> symbols = '$¢£¥€¤'
>>> beyond_ascii = list(filter(lambda c: c > 127, map(ord, symbols)))


사용 O

>>> symbols = '$¢£¥€¤'
>>> beyond_ascii = [ord(s) for s in symbols if ord(s) > 127]


4. Cartesian Products

>>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> tshirts = [(color, size) for color in colors for size in sizes]


5. Generator Expressions

Generator Expression 장점 : MEMORY SAVE

  • yields items “one by one” using iterator protocol
  • instead of building a whole list


>>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> for tshirt in ('%s %s' % (c, s) for c in colors for s in sizes):
... print(tshirt)


6-1. Tuple의 역할 1 : Tuples as Records

Tuples as Records

lax_coordinates = (33.9425, -118.408056)
city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014)


Tuple Unpacking ( 참고로, list도 됨 )

lax_coordinates = (33.9425, -118.408056)
latitude, longitude = lax_coordinates
  • prefix argument with start(*)

    >>> t = (20, 8)
    >>> divmod(*t)
    (2, 4)
    


Star(*)로 잔여 요소 잡기

>>> a, b, *rest = range(5)
>>> rest
[2, 3, 4]


Named Tuples

collections.namedtuple :

  • produces subclasses of tuple
>>> from collections import namedtuple

>>> City = namedtuple('City', 'name country population coordinates')
>>> tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
>>> tokyo
City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722,
139.691667))

>>> tokyo.population
36.933

>>> tokyo.coordinates
(35.689722, 139.691667)

>>> tokyo[1]
'JP'


6-2. Tuple의 역할 2 : Immutable Lists

list와 비교해서….

  • adding & removing item 불가!

  • reversed 불가!


7. Slicing

1) 1-Dimensional Slicing

>>> s = 'bicycle'

>>> s[::3]
'bye'

>>> s[::-1]
'elcycib'

>>> s[::-2]
'eccb'


2) Multi-dimensional Slicing & Ellipsis

a[i.j] = a.__getitem__((i,j))

ellipsis

  • 세 개의 점 (…)

  • example)

    x[i,...] = x[i,:,:,:,]


8. Lists of Lists

방법 1)

>>> board = [['_'] * 3 for i in range(3)]
>>> board[1][2] = 'X'

>>> board
[['_', '_', '_'], ['_', '_', 'X'], ['_', '_', '_']]

위를 풀어보면.. ( 셋이 다 다른 애 )

board = []
for i in range(3):
	row = ['_'] * 3 
    board.append(row)


방법 2)

>>> weird_board = [['_'] * 3] * 3
>>> weird_board[1][2] = 'O'

>>> weird_board
[['_', '_', 'O'], ['_', '_', 'O'], ['_', '_', 'O']]

위를 풀어보면.. ( 셋이 다 같은 애 )

row = ['_'] * 3
board = []
for i in range(3):
    board.append(row)


9. Augmented Assignment with Sequences

+= = __iadd__ ( in-place addition )

+* = __imul__ ( in-place multiplication )


10. sort vs sorted

list.sort() : in place ( 복사 X )

sorted(list) : 복사 O


list.sort()

fruits = ['grape', 'raspberry', 'apple', 'banana']
id1=id(fruits)
fruits.sort()
id2=id(fruits)

id1==id2 # TRUE


sorted(list)

fruits1 = ['grape', 'raspberry', 'apple', 'banana']
fruits2 = sorted(fruits1)

id(fruits1)==id(fruits2) # FALSE


11. When a List is Not the Answer

리스트 : flexible & easy

(대안 1)

  • 하지만, 10 million floating-point 값을 가진다면, array가 더 효율적! ( ex. numpy array )

(대안 2)

  • 지속적으로 값을 추가/제거 한다면, deque ( double-ended queue ) 가 더 낫다!


pickle 모듈

  • fast & flexible way of saving numeric data
  • pickle.dump


12. numpy

reshape하는 방법 2가지

a = np.arange(12)

# 방법 1)
a = a.reshape(3,4)

# 방법 2)
a.shape = 3,4


파일 불러오기, 저장하기

file = np.loadtxt('aaaaa.txt')

np.save('myfile',x)
x = np.load('myfile.npy','r+')


13. Deques & other Queues

list를 stack/queue처럼 사용하기!

  • .append()
  • .pop()

하지만, insert/removing 하는 것은, “전체 list를 옮겨야”하므로, costly!

따라서, collections.deque 를 사용하자!


from collections import deque

dq = deque(range(10), maxlen=10)


dq.rotate(3) # ->->-> 
dq
# deque([7, 8, 9, 0, 1, 2, 3, 4, 5, 6], maxlen=10)

dq.rotate(-4) # <-<-<-<-
dq
# deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], maxlen=10)

dq.appendleft(-1) # 왼쪽에 1개 추가 ( 가장 오른쪽 값 bye )
dq
# deque([-1, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)

dq.extend([11, 22, 33]) # 오른쪽에 list 추가 ( 가장 왼쪽 값들 bye )
dq
# deque([3, 4, 5, 6, 7, 8, 9, 11, 22, 33], maxlen=10)

dq.extendleft([10, 20, 30, 40]) # 왼쪽에 list 추가 ( 가장 오른쪽 값들 bye )
dq
# deque([40, 30, 20, 10, 3, 4, 5, 6, 7, 8], maxlen=10)

Tags:

Categories:

Updated: