'Python' 태그의 글 목록 (5 Page)
본문 바로가기

Python53

Reverse list - 리스트 역순으로 list의 reverse 방법은 list.reverse(), reversed(list), list[::-1], [list.pop() for _ in list] 가 있다 더 있으면 리플달아주세요. 속도는 아래 순이다 list.reverse() < list[::-1] < reversed(list) < [list.pop() for _ in list] l=list(range(2000000)) fidx=1999999 @print_method def use_reverse(): tl = l[:] tl.reverse() print(tl[fidx]) @print_method def use_reversed(): # list를 새로 만든다 tl = l[:] tl = list(reversed(tl)) print(tl[fidx.. 2020. 9. 16.
list method 성능 측정 list 를 만들 때, +, append, comprehension 등을 사용한다 각각의 성능측정 결과, 상황에 맞게 잘 사용하면 좋을 것 같다 le = 1000000 @print_method def test_concat(): # O(k) l=[] for i in range(le): l+=[i] @print_method def test_append(): # O(1) l=[] for i in range(le): l.append(i) @print_method def test_comprehension(): l=[i for i in range(le)] @print_method def test_range(): l=list(range(le)) test_concat() test_append() test_compreh.. 2020. 9. 15.
Index(), bisect() - list 원소의 index값 찾기 list의 index값을 찾는 방법 index를 찾는 list의 크기가 크거나 loop로 찾는다면 bisect() 이진분할 알고리즘을 사용하면 시간을 단축할 수 있다 list.index(n) # list index함수 bisect(list, n) # 이진분할 알고리즘 rmax = 2000000 l = [i for i in range(rmax)] loop = 50 find_n = rmax-2 @print_time def m_index(): for i in range(loop): l.index(find_n) import bisect @print_time def m_bisect(): for i in range(loop): idx = bisect.bisect_left(l, find_n) m_index() m_b.. 2020. 9. 14.
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.