본문 바로가기

Python50

named tuple - 네임드듀플 namedtuple은 tuple과 비슷한 성능과 특성을 갖는다 tuple 항목을 index 위치뿐 아니라 name으로도 참조할 수 있다 >>> from collections import namedtuple >>> >>> Animal = namedtuple('Animal', 'name species sex') >>> # Animal = namedtuple('Animal', ['name','species','sex']) ... # Animal = namedtuple('Animal', ('name','species','sex')) ... a = Animal('pororo', 'penguin', 'male') >>> a Animal(name='pororo', species='penguin', sex='male'.. 2020. 9. 11.
permutations in itertools permutations(순열) 서로다른 n개의 원소에서 서로 다른 r개의 원소를 선택하여 나열한 것 # 순열: 서로다른 n개의 원소에서 서로 다른 r개의 원소를 선택하여 나열한 것 from itertools import permutations data = 'ABC' n = len(data) r = 2 result = list(permutations(data, r)) print(result) [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')] print([''.join(dp) for dp in result]) ['AB', 'AC', 'BA', 'BC', 'CA', 'CB'] 2020. 9. 4.
list[::], tuple[::] - extended slices python에서 list, tuple를 자를 때, 효과적인 방법 list[start index:end index+1:step] >>> list_int = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # slice >>> list_int[:2] [0, 1] >>> list_int[0:2] [0, 1] >>> list_int[:5] [0, 1, 2, 3, 4] >>> list_int[2:5] [2, 3, 4] >>> list_int[::1] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # even >>> list_int[::2] [0, 2, 4, 6, 8] # odd >>> list_int[1::2] [1, 3, 5, 7, 9] >>> list_int[::3] [0, 3, 6, 9] #.. 2020. 9. 2.
index(), find() - 원소의 인덱스 index(), find() 메소드는 원소의 인덱스 위치를 반환한다 index()는 해당 원소가 없으면 ValueError를 리턴하고, find()는 -1을 리턴한다 find()는 문자열에서만 지원한다 # tuple >>> (1,2,3,4).index(2) 1 >>> (1,2,3,4).index(5) Traceback (most recent call last): File "", line 1, in ValueError: tuple.index(x): x not in tuple >>> (1,2,3,4).find(2) Traceback (most recent call last): File "", line 1, in AttributeError: 'tuple' object has no attribute 'find'.. 2020. 9. 1.
string unpacking - 문자열 언팩킹 언팩킹이란? 요소를 여러 변수에 나누어 담는 것 locals()? 현재 scope 에 있는 local 변수를 딕셔너리 type( {key:value} ) 으로 반환 >>> nums = [1,2,3,4] # unpacking >>> a,*b = nums >>> a 1 >>> b [2,3,4] >>> f'{a} {b} {nums}' 1 [2,3,4] [1,2,3,4] # unpacking >>> '{a} {b} {nums}'.format(**locals()) 1 [2,3,4] [1,2,3,4] 2020. 8. 23.
generator - 제너레이터 제너레이터는 파이썬의 시퀀스를 생성하는 객체다 전체 시퀀스를 한 번에 메모리에 생성하고 정렬할 필요없이, 잠재적으로 아주 큰 시퀀스를 순회할 수 있다 제너레이터를 순회할 때마다 마지막으로 호출된 요소를 기억하고 다음 값을 반환한다 제너레이터 함수는 yield문을 사용한다 2020. 8. 18.