더북(TheBook)

하지만 누락된 데이터에 보초 값(sentinel value)을 채우는 것이 더 나을 때도 분명 있습니다. 보초 값은 데이터에 대해 ‘특별한’ 상황을 표시할 수 있는 특별한 값입니다. 대부분의 경우 None이 보초 값으로 사용되지만, 양수(positive)가 정상인 상황일 때는 -1과 같은 음수를 보초 값으로 사용하는 경우도 있습니다. 이외에도 my_sentinel = object()와 같이 정의하여 다른 데이터와 확실하게 구분되는 특별한 값을 사용할 수도 있습니다. zip_longest()를 사용하면 누락된 데이터를 쉽게 채울 수 있습니다.

itertools.zip_longest()를 사용해 누락된 데이터 채우기

>>> from itertools import zip_longest
>>> stations = []
>>> with (
...     open("station-names.txt") as names,
...     open("station-lattrunc.txt") as lats,
...     open("station-longitudes.txt") as lons,
...     open("station-elevations.txt") as els,
... ):
...     for datum in zip_longest(names, lats, lons, els, fillvalue="-1"):
...         datum = (d.rstrip() for d in datum)
...         stations.append(Station(*datum))

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.