◾ord(문자)
cf) 중요 아스키코드
◾lower(), upper()
◾islower(), isupper()
◾isspace()
◾isdigit(), isalpha(), isalnum()
◾capitalize() / title()
str = "abc-def efg"
print(str.capitalize()) #Abc-def efg
print(str.title()) #Abc-Def Efg
◾find
# "s"가 위치한 index 찾기
# 여러 개일 경우 가장 앞쪽 index
print(s.find("s")) # 7
◾replace()로 특정 문자 제거
str = "Hello, World, Python"
new_str = str.replace(',', '')
print(new_str)
str = "Hello, World, Python"
new_str = str.replace(',', '', 1)
print(new_str)
import re
str = "Hello, World, Python"
result = re.sub(",|He|Py", "", str)
print(result)
◾10진수에서 2진수, 8진수, 16진수 변환 bin, oct, hex
value = 60
b = bin(value)
o = oct(value)
h = hex(value)
print(b)
print(o)
print(h)
# 0b111100
# 0o74
# 0x3c
cf) 0~ 빼고 나오도록 format(숫자, 형식)
value = 60
b = format(value, 'b')
o = format(value, 'o')
h = format(value, 'x')
print(b)
print(o)
print(h)
# 111100
# 74
# 3c
↔ 10진수로 변환 int
b = int('0b111100', 2)
o = int('0o74', 8)
h = int('0x3c', 16)
◾abs
절댓값
◾put
◾get()
import queue
data = queue.Queue()
data.put(2)
print(data.get())
◾append
◾pop()
stack = []
stack.append(2)
print(stack.pop())
top = stack[-1]
print(top)
리스트
1. list.sort()
array = [['a', 1], ['c', 4], ['b', 3], ['d', 2]]
array.sort(key = lambda x:x[0]) # array.sort() 와 동일.
2. sorted(list)
array = [['a', 1], ['c', 4], ['b', 3], ['d', 2]]
array2 = sorted(array, key = lambda x:x[1])
print("1번째 값을 key 값으로 정렬 :", array2)
# > 1번째 값을 key 값으로 정렬 : [['a', 1], ['d', 2], ['b', 3], ['c', 4]]
# reverse = True로 내림차순 설정 가능
딕셔너리
1. key 기준 정렬(오름차순)
my_dict = {'c': 3, 'a': 1, 'b': 2, 'e': 1, 'd': 2}
sorted_dict = sorted(my_dict.items())
print(sorted_dict)
2. key 기준 정렬(내림차순)
sorted_dict = sorted(my_dict.items(), key = lambda item: item[0], reverse = True)
print(sorted_dict)
item[0] 대신 item[1]을 쓰면 value 기준 정렬이 됨.
◾add(원소 한 개)
#값 1개만 추가하기 - add
>>> s1 = set([1, 2, 3])
>>> s1.add(4)
>>> s1
{1, 2, 3, 4}
◾update(원소 여러 개 list)
#값 여러 개 추가하기 - update
>>> s1 = set([1, 2, 3])
>>> s1.update([4, 5, 6])
>>> s1
{1, 2, 3, 4, 5, 6}
◾remove(특정 값)
#특정 값 제거하기 - remove
>>> s1 = set([1, 2, 3])
>>> s1.remove(2)
>>> s1
{1, 3}
스택
◾append()
◾pop()
큐
◾appendleft()
◾popleft()
◾append()
◾pop()
리스트
◾insert(추가할 인덱스, 추가할 항목)
◾remove(삭제할 항목)
◾extend()
◾extendleft()
#deque 앞(왼쪽)에 iterable 객체를 순환하며 값들을 차례로 추가
#(주의! 객체의 마지막 값부터 deque에 추가)
dq.extendleft([2, 1, 0])
print(dq) # print결과 : deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
◾reverse()
◾rotate()
◾append
◾pop
◾insert
# a.insert(i, v) : i번 인덱스에 v 추가
a.insert(3, 7) # [1, 2, 3, 7, 4, 5, 6]
◾remove
# a.remove(v) : v 값을 찾아서 제거
# 없는 값을 제거할 경우 ValueError: list.remove(x): x not in list 에러 발생
a.remove(4) # [1, 2, 3, 5]
# 참고) 특정 index의 값을 제거하려면 del 키워드 사용
del a[3] # 2번 index 원소 삭제
◾index
# a.index(v) : v가 리스트의 몇 번째 index에 있는지 반환
print(a.index(5)) # 3
◾min, max, sum
◾reverse
◾clear: 리스트 비우기
◾all, any
a = [11, 12, 42, 38, 7]
# all(iterable 리스트, 튜플, 딕셔너리 등)
# 모든 요소가 참이면 True, 하나라도 거짓이면 False
a = [11, 12, 42, 38, 7]
if all(60 > x for x in a):
print("모든 원소가 60 미만입니다.")
# all(iterable 리스트, 튜플, 딕셔너리 등)
# 요소가 하나라도 참이면 True, 전부 거짓이면 False
if any(10 > x for x in a):
print("10미만인 원소가 존재합니다.")
◾filter
string = '0001100'
res = list(filter(lambda x: string[x]=='0', range(len(string))))
>>> [0, 1, 2, 5, 6]
◾count(특정 값)
특정값 수 세기
nums = [a, b, c, d]
counts = [nums.count(i) for i in nums]
original_list = [1, 2, 3, 4, 2, 5, 2]
value_to_remove = 2
new_list = [x for x in original_list if x != value_to_remove]
original_list = [1, 2, 3, 4, 2, 5, 2]
value_to_remove = 2
while value_to_remove in original_list:
original_list.remove(value_to_remove)
◾count
◾index
# 여러 개면 가장 앞쪽 인덱스, 없으면 에러
s.index(2) # 1
bb = {v:k for k,v in aa.items()}
del aa['key_name']
◾put
◾get
from queue import PriorityQueue
q = PriorityQueue(maxsize=10) # 크기 제한
q.put(3)
# or
q. put((1, 'apple')) # 1:우선순위, 'apple':값
q.get()
q1.get()[1] # (우선순위, 값)의 형태에서 값 반환
import heapq
hq = []
heapq.heappush(hq, 4)
heapq.heappush(hq, 1)
heapq.heappush(hq, 3)
heapq.heappush(hq, 7) # [4,1,3,7]
heapq.heappop(hq) # 1
heapq.heapify(x) # [3,4,7]
참고:
https://dev-note-97.tistory.com/13
https://choiiis.github.io/python/for-coding-test/