[문법]내가 자주 까먹는 파이썬 문법

CHOI YUN HO·2021년 1월 29일
0

나만의 노트

목록 보기
1/6
post-thumbnail

알고리즘 문제를 풀다보면 종종(?) 쓰는데 자주(?) 까먹는 문법들이 있다.

근데 매번 찾아보기가 귀찮아서
여기에 다 정리해놓고 나만 볼랭~

1. 기본

  • a ** b >>> a^b
  • a // b >>> 몫을 정수로 구하고 싶을 때
  • a, b = b, a >>> SWAP
  • "".join(list) >>> 리스트를 문자열로
  • 람다 표현식
  • append, extend

2. 정렬

arr = [1, 10, 5]
arr.sort()
#[1, 5, 10]

arr.sort(reverse=True)
#[10, 5, 1]

arr2 = [[1,2], [1,2,3], [1]]
arr2.sort(key=len)
#[[1], [1,2], [1,2,3]]

3. 반복문

A = [1, 2, 3]
B = [4, 5, 6]
for a, b in zip(A, B):
        print(a, b)
        # 1 4
        # 2 5
        # 3 6

for p in enumerate(A):
	print(p)
    # (0, 1)
    # (1 ,2)
    # ...

for i, v in enumerate(A):
	print(i, v)
    # (0, 1)
    # (1 ,2)
    # ...

4. 순열과 조합

  • 순열
from itertools import permutations

permutations([1,2,3,4], 2)
# [(1,2), (1,3), (1,4), (2,1), (2,3), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,3)]
  • 조합
from itertools import combinations

combinations([1,2,3,4], 2)
# [(1,2), (1,3), (1,4), (2,3), (2,4), (3,4)]
  • 두 개 이상의 리스트에서 조합 구하기
from itertools import product

items = [['a', 'b', 'c,'], ['1', '2', '3', '4'], ['!', '@', '#']]
list(product(*items))
# [('a', '1', '!'), ('a', '1', '@'), ('a', '1', '#'), ('a', '2', '!'), ('a', '2', '@'), ('a', '2', '#'), ('a', '3', '!'), ('a', '3', '@'), ('a', '3', '#'), ('a', '4', '!'), ('a', '4', '@'), ('a', '4', '#'), ('b', '1', '!'), ('b', '1', '@'), ('b', '1', '#'), ('b', '2', '!'), ('b', '2', '@'), ('b', '2', '#'), ('b', '3', '!'), ('b', '3', '@'), ('b', '3', '#'), ('b', '4', '!'), ('b', '4', '@'), ('b', '4', '#'), ('c,', '1', '!'), ('c,', '1', '@'), ('c,', '1', '#'), ('c,', '2', '!'), ('c,', '2', '@'), ('c,', '2', '#'), ('c,', '3', '!'), ('c,', '3', '@'), ('c,', '3', '#'), ('c,', '4', '!'), ('c,', '4', '@'), ('c,', '4', '#')]

5. 딕셔너리

# 딕셔너리 선언 
dic = {}
dic['a'] = 1
//
dic = {'a' : 1}

# 삭제
del dic['a']

# key와 value에 각각 접근
for key, value in dic.items():
	print(key, value)

dic.keys(), dic.values()

# 정렬
sorted(dic.items(), key=lambda x: x[1])

# 없으면 0, 있으면 1 더하기
dic[key] = dic.get(key, 0) + 1

# 밸류의 최대값이 여러개일 때 해당 key가져오기
[k for k, v in dic.items() if max(dic.values())]        

6. ASCII

ord('A')
profile
가재같은 사람

0개의 댓글