티스토리 뷰

728x90
반응형

Python Code Snippet

리스트를 문자열로 바꾸면서 앞, 뒤에 문자열 추가하고 중간 중간에 들어갈 문자열도 직접 지정하기

iu = ["1", "2", "3"]
print("<",", ".join(iu),">", sep='')
# 결과 : <1, 2, 3>



리스트 2개 이상의 기준으로 정렬하기

iu = [[4,3],[2,1]]
iu.sort(key=lambda x: (x[0], x[1]))
print(iu) # [[2, 1], [4, 3]]



리스트에서 특정 단어 및 숫자의 인덱스가 여러개 있을 때

test_list = [1, 3, 4, 3, 6, 7]
print("Original list : " + str(test_list))
res_list = list(filter(lambda x: test_list[x] == 3, range(len(test_list))))
print("New indices list : " + str(res_list))

# Original list : [1, 3, 4, 3, 6, 7]
# New indices list : [1, 3]



이진검색모듈 bissect

from bisect import bisect_left, bisect_right

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 5
print(bisect_left(nums, n))
print(bisect_right(nums, n)) 
# 결과값 5 6
from bisect import bisect_left, bisect_right

nums = [4, 5, 5, 5, 5, 5, 5, 5, 5, 6]
n = 5
print(bisect_left(nums, n))
print(bisect_right(nums, n))
# 결과값 1 9

bisect_left는 인덱스범위의 왼쪽 값, bisect_right는 인덱스 범위의 오른쪽 값 + 1임.
결국 인덱싱할 때 이거 2개쓰면 범위부분 다 인덱싱 가능



이차원 배열 초기화 할 때

visited = [[False] * 3 for tmp in range(3)]
visited[1][1] = True
print(visited)
# [[False, False, False], [False, True, False], [False, False, False]]

안그럼 한줄 같은 객체로 인식해서 값 넣을 때 한 줄 같이 넣어짐.



Counter.items()

import collections
ex = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'c', 'a', 'd', 'd', 'd']
count = collections.Counter(ex)

for key, value in count.items():
    print(key, value)
"""
a 4
b 2
c 4
d 3
"""



Counter substract 내부함수

import collections
ex = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'c', 'a', 'd', 'd', 'd']
count = collections.Counter(ex)

print(count.most_common())
count.subtract('a') # counter 갯수를 한개 줄임
print(count.most_common())

"""
[('a', 4), ('c', 4), ('d', 3), ('b', 2)]
[('c', 4), ('a', 3), ('d', 3), ('b', 2)]
"""



Counter 모듈 유용한 핵(?). Counter에서 0이하인거 없애기.

import collections
ex = ['a', 'b', 'b', 'c', 'c', 'c', 'c', 'd', 'd', 'd']
count = collections.Counter(ex)
count.subtract('a') # 'a'가 1개 있었는데 빼줘서 0개임 
count += collections.Counter() # Counter에서 0인걸 삭제 해주는 코드임. 
print(count) # Counter({'c': 4, 'd': 3, 'b': 2})



orderedDict popitem 쓰는법

defaultDict 처럼 쓴다음 popitem으로 그대로 뽑으면 value 가장 큰거 순으로 pop 됨.

import collections

ex = collections.OrderedDict()

ex['A'] = 1
ex['B'] = 2
ex['C'] = 3
for key, value in ex.items():
    print(key, value)
"""
A 1
B 2
C 3
"""

dict 와 비교하기 참고



2차원 리스트 복사

import copy

iu = [[0,0,1,1],[1,1,0,0]]
IU = copy.deepcopy(iu)
iu[0][0] = 1
print(iu)
print(IU)

"""
[[1, 0, 1, 1], [1, 1, 0, 0]]
[[0, 0, 1, 1], [1, 1, 0, 0]]
"""



리스트 요소의 인덱스 2개 이상 뽑기

uaena = ['u', 'a', 'e', 'n', 'a', 'u', 'a', 'e', 'n', 'a']
print([i for i, value in enumerate(uaena) if value == 'u'])
# [0, 5]



다른 진수의 형태로 숫자를 표현하기

2, 8, 16진수 숫자 앞에 0b, 0o, 0x 붙이면됨.

>>> 42 == 0b101010
>>> 42 == 0o52
>>> 42 == 0x2a
# 모두 True



숫자에서 다른 진수의 문자열로 변환하기

>>> bin(42)
'0b101010'
>>> oct(42)
'0o52'
>>> hex(42)
'0x2a'



다른 진수의 문자열로 숫자형으로 변환하기

>>> int('0b101010', 2)
42
>>> int('0o52', 8)
42
>>> int('0x2a', 16)
42



이분탐색 범위 템플릿

def search_while(self, nums: List[int], target: int) -> int:
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = (left + right) // 2

        if nums[mid] < target:
            left = mid + 1
        elif nums[mid] > target:
            right = mid - 1
        else:
            return mid
    return -1
  • left, right 범위 포함
  • left <= right
  • mid + 1, mid -1
728x90
반응형
댓글
반응형
250x250
글 보관함
최근에 달린 댓글
«   2024/05   »
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
링크