Home Python 문법
Post
Cancel

Python 문법

πŸ“š 리슀트

μ»΄ν”„λ¦¬ν—¨μ…˜

λŒ€κ΄„ν˜Έ μ•ˆμ— 쑰건문과 λ°˜λ³΅λ¬Έμ„ μ μš©ν•˜μ—¬ 리슀트λ₯Ό μ΄ˆκΈ°ν™”ν•˜λŠ” 방법

1
a = [i for i in range(5)]


λ¦¬μŠ€νŠΈμ—μ„œ νŠΉμ • 값을 κ°€μ§€λŠ” μ›μ†Œλ₯Ό λͺ¨λ‘ μ œκ±°ν•˜κΈ°

1
2
3
4
5
arr = [1, 1, 2, 2, 3]
search = {1, 2}

# arr에 1, 2λ₯Ό μ œμ™Έν•œ κ°’λ§Œ μ €μž₯
res = [a for a in arr if a not in search]


리슀트 κ΄€λ ¨ λ©”μ„œλ“œμ˜ μ‹œκ°„ λ³΅μž‘λ„

ν•¨μˆ˜λͺ…μ‹œκ°„ λ³΅μž‘λ„
append()O(1)
sort()O(NlogN)
reverse()O(N)
insert()O(N)
count()O(N)
remove()O(N)



πŸ“š νŠœν”Œ

νŠΉμ§•

  • νŠœν”Œμ€ ν•œ 번 μ„ μ–Έλœ 값을 λ³€κ²½ν•  수 μ—†λ‹€.
  • νŠœν”Œμ€ λ¦¬μŠ€νŠΈμ— λΉ„ν•΄ μƒλŒ€μ μœΌλ‘œ 곡간 νš¨μœ¨μ μ΄λ‹€.
  • νŠœν”Œμ„ λΉ„λ‘―ν•˜μ—¬ λ¦¬μŠ€νŠΈλŠ” μˆœμ„œκ°€ μ‘΄μž¬ν•œλ‹€.


νŠœν”Œμ€ μ‚¬μš©ν•˜λ©΄ 쒋은 경우

  • μ„œλ‘œ λ‹€λ₯Έ μ„±μ§ˆμ˜ 데이터λ₯Ό λ¬Άμ–΄μ„œ 관리해야 ν•˜λŠ” 경우
  • λ©”λͺ¨λ¦¬λ₯Ό 효율적으둜 μ‚¬μš©ν•΄μ•Ό ν•˜λŠ” 경우



πŸ“š μ§‘ν•©

set()

  • 쀑볡을 ν—ˆμš©ν•˜μ§€ μ•ŠλŠ”λ‹€.
  • μˆœμ„œκ°€ μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ”λ‹€.
  • 사전 μžλ£Œν˜•κ³Ό μ§‘ν•© μžλ£Œν˜•μ€ μˆœμ„œκ°€ μ—†κΈ° λ•Œλ¬Έμ— 검색할 λ•Œ O(1)의 μ‹œκ°„ λ³΅μž‘λ„λ₯Ό κ°€μ§„λ‹€.


μ§‘ν•© μžλ£Œν˜• μ—°μ‚°

1
2
3
4
5
6
7
8
9
10
11
12
13
14
s1 = {1, 2, 3}
s2 = {3, 4}

# ν•©μ§‘ν•©
print(s1 | s2)
print(s2.union(s1))

# ꡐ집합
print(s1 & s2)
print(s1.intersection(s2))

# ν•©μ§‘ν•©
print(s1 - s2)
print(s1.difference(s2))



πŸ“š ν•¨μˆ˜

eval()

1
2
# λ¬Έμžμ—΄ ν˜•νƒœμ˜ 식을 κ³„μ‚°ν•΄μ£ΌλŠ” ν•¨μˆ˜
print(eval("2+3"))

λ§Œμ•½, ν”Όμ—°μ‚°μž μ•žμ— 0이 λΆ™μ–΄ μžˆλŠ” 경우, 였λ₯˜κ°€ λ°œμƒν•œλ‹€. (Ex. 1+01)



πŸ“š 라이브러리

itertools

1
2
3
4
5
6
7
8
9
10
11
# μˆœμ—΄ : μ„œλ‘œ λ‹€λ₯Έ nκ°œμ—μ„œ μ„œλ‘œ λ‹€λ₯Έ r개λ₯Ό μ„ νƒν•˜μ—¬ λ‚˜μ—΄
from itertools import permutations

# μ‘°ν•© : μ„œλ‘œ λ‹€λ₯Έ nκ°œμ—μ„œ μˆœμ„œμ™€ 상관 없이 μ„œλ‘œ λ‹€λ₯Έ r개 선택
from itertools import combinations

# 쀑볡 μˆœμ—΄ : 쀑볡 κ°€λŠ₯ν•œ nκ°œμ—μ„œ r개λ₯Ό μ„ νƒν•˜μ—¬ λ‚˜μ—΄
from itertools import product

# 쀑볡 μ‘°ν•© : 쀑볡 κ°€λŠ₯ν•œ nκ°œμ—μ„œ μˆœμ„œμ™€ 상관 없이 r개 선택
from itertools import combinationswith_replacement


collections

1
2
3
4
5
6
7
8
9
10
11
# μΉ΄μš΄νŒ…
from collections import Counter

a = ['apple', 'banana', 'apple']
counter = Counter(a)

# μ—…λ°μ΄νŠΈ
counter.update(a)

# κ°€μž₯ λΉˆλ„κ°€ 높은 순으둜 n개 좜λ ₯
print(counter.most_common(n))
1
2
3
4
5
6
7
8
# 큐 κ΅¬ν˜„
# 리슀트λ₯Ό μ‚¬μš©ν•˜λŠ” κ²½μš°λ³΄λ‹€ νš¨μœ¨μ„±μ΄ λ†’λ‹€.
from collections import deque

queue = deque()

queue.append(1)
queue.popleft()
This post is licensed under CC BY 4.0 by the author.