Python ์ฒ์ ์ ํ๋ ์ฌ๋๋ค์ด ํ๋ ํํ ์ค์
1) try ~ except~ ๊ตฌ๋ฌธ
๊ตฌ๋ฌธ ์ฌ์ฉํ ๋ error๋ฌธ์ ์ง์ ๊ทธ๊ฒ๋ ์ด์ํ๊ฒ ์์ฑํ๋ ๊ฒฝ์ฐ๊ฐ ๋ง๋ค. python์์ ์ฌ์ฉํ๋ error ๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ฉด ๋ ์ผ์ ๋๋ง์ด ์์๋ณด๊ฒ ํด๋๋๊ฒ์ด ํฐ ์ค์๋ก ์ด์ด์ง๋ค.
[Worse]
total: float = 0
while True:
user_input: str = input("Add: ")
try:
total += float(user_input)
except:
print('์ซ์๋ง ์
๋ ฅํด์ฃผ์์ค.')
print(f"Current: {total}")
[Better]
total: float = 0
while True:
user_input: str = input("Add: ")
try:
total += float(user_input)
except Exception as e:
print(repr(e))
print(f"Current: {total}")
2) type ์ ์ธ
static ๋ณ์๋ฅผ ์ฌ์ฉํด append ํจ์๋ฅผ ๋ง๋ค์ด ๋ณด์.
[Worse]
from typing import Iterable, TypeVar, Any
T = TypeVar('T') # static type checking
def append_to_list(elements: Iterable[T], target: list[T]=[]) -> list[Any]:
target.extend(elements)
return target
print(append_to_list([1, 2])) # [1, 2]
print(append_to_list([3, 4])) # [1, 2, 3, 4]
print(append_to_list([5, 6],[])) # ??? [5, 6]
print(append_to_list(["a","b"])) # [1, 2, 3, 4, 5, 6, 'a', 'b']
์ ๊ฒฐ๊ณผ ๊ธฐ์กด์ ๋ณ์๊ฐ ๋จ์ List append๊ฐ ๋๋ ๊ฒ์ ๋ณผ ์ ์๋ค.
append_to_list์ target์ด ์์ ๋ ์์๋ ๋๋์ด ํจ์๋ฅผ ๋ง๋ค๋ฉด ๊ธฐ์กด list๋ฅผ ์ฐธ์กฐํ์ง ์๊ณ ๋๊ธธ ์ ์๋ค.
[Better]
from typing import Iterable, TypeVar, Any
T = TypeVar('T') # static type checking
def append_to_list(elements: Iterable[T], target: list[T]=None) -> list[Any]:
if target is None:
target = []
target.extend(elements)
return target
print(append_to_list([1, 2])) # [1, 2]
print(append_to_list([3, 4])) # [3, 4]
print(append_to_list([5, 6],[])) # [5, 6]
print(append_to_list(["a","b"],["c"])) # ["a", "b", "c"]
3) ๋ ์ด์ range๋ฅผ ๋ฌด์ํ์ง ๋ง๋ผ
range๋ฅผ ๋ค์ list๋ก ๋ฐ์ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ๊ฐ ์๋ค. ์ด ๊ฒฝ์ฐ range์์ ์ฌ์ฉํ iteration์ ๋ชจ๋ list์ ๋ด์์ผํ๊ธฐ ๋๋ฌธ์ ๋ฉ๋ชจ๋ฆฌ๊ฐ ์๋นํ ๋์ด๋๋ค.
from sys import getsizeof
my_range : range = range(10**6)
print(type(my_range))
print(getsizeof(my_range), 'bytes')
# <class 'range'>
# 48 bytes
my_range : list[int] = list(range(10**6))
print(type(my_range))
print(getsizeof(my_range), 'bytes')
# <class 'list'>
# 8000056 bytes
range, map, filter ์ด ์ฒ๋ผ iteration์ ์ฌ์ฉํ๋ ํจ์์ ๊ฒฝ์ฐ ๋ณํ์ ํ์ง ์๊ณ ์ฌ์ฉํ๋ ๊ฒ์ด ๊ฐ์ฅ ๋น ๋ฅด๋ค.
'๐ Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
string method. 1~20 (0) | 2024.04.28 |
---|---|
[Python] f-string trick (2) (0) | 2024.03.17 |
[Python] f-string trick (1) (0) | 2024.03.02 |
FastAPI - starlette.routing.NoMatchFound: No route exists for name (0) | 2024.01.19 |
[pip] WARNING: Skipping due to invalid metadata entry 'name' (0) | 2023.12.30 |