이전 포스트
자주 쓰는 Powershell 명령어 모음
자주 쓰는 Powershell 명령어를 모았다
print(f"{len(words):,}")
for i, item in enumerate(items):
process(i, item)
print(ord('A')) # 출력: 65
print(ord('가')) # 출력: 44032
before
val = get_data()
while not predicate(val):
print("Current value acceptable:", val)
after
while not predicate(val := get_data()):
print("Current value acceptable:", val)
another examples
if (match := pattern.search(data)) is not None:
print("Found:", match.group(0))
results = [y := f(x), y**2, y**3 for x in range(5)]
# 점수를 저장하는 namedtuple 정의
Score = namedtuple('Score', ['name', 'points'])
# 여러 점수 저장
scores = [
Score('Alice', 95),
Score('Bob', 87),
Score('Charlie', 92)
]
# 이름을 통해 데이터 접근
for score in scores:
print(f'{score.name} scored {score.points} points.')
읽기
from pathlib import Path
content = Path("station-names.txt").read_text()
class MyContextManager:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting the context")
if exc_type:
print(f"An exception occurred: {exc_val}")
return True # 예외를 처리했음을 알림 (False일 경우 예외가 재발생)
with MyContextManager() as manager:
print("Inside the context")
# raise ValueError("Something went wrong") # 예외가 발생하더라도 __exit__가 실행됨
with (
open("station-names.txt") as names,
open("station-latitudes.txt") as lats,
open("station-longitudes.txt") as lons,
open("station-elevations.txt") as els
):
for data in zip(names, lats, lons, els):
data = (field.rstrip() for field in data)
import pprint
data = [
{'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'gardening']},
{'name': 'Bob', 'age': 25, 'hobbies': ['gaming', 'coding']},
{'name': 'Charlie', 'age': 35, 'hobbies': ['hiking', 'swimming']}
]
pprint.pprint(data)
Output
[{'age': 30, 'hobbies': ['reading', 'gardening'], 'name': 'Alice'},
{'age': 25, 'hobbies': ['gaming', 'coding'], 'name': 'Bob'},
{'age': 35, 'hobbies': ['hiking', 'swimming'], 'name': 'Charlie'}]
with open('example.txt') as fd:
for line in fd:
line = line.rstrip() # 개행 문자 제거
print(repr(line))
@ 윈도우의 개행은 \r\n 이지만 open으로 파일을 읽으면 \n으로 자동 변환됨. 이게 싫으면 open으로 열때 rb로 열것
x = 10
print(repr(x)) # 출력: '10'
text = "Hello, world!"
print(repr(text)) # 출력: "'Hello, world!'"
my_list = [1, 2, 3]
print(repr(my_list)) # 출력: '[1, 2, 3]'
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
zipped = zip(a, b)
print(list(zipped)) # 출력: [(1, 'a'), (2, 'b'), (3, 'c')]
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
try:
zipped_strict = zip(a, b, strict=True)
print(list(zipped_strict))
except ValueError as e:
print(e) # 출력: zip() argument 2 is longer than argument 1
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
try:
zipped_strict = zip(a, b, strict=True)
print(list(zipped_strict))
except ValueError as e:
print(e) # 출력: zip() argument 2 is longer than argument 1