시작하기무료로 시작하기

Dataclass 활용하기

이전 연습 문제에서 만든 WeightEntry dataclass를 실제로 사용해 보겠습니다. weight_log의 각 항목마다 WeightEntry 인스턴스를 만든 다음, 우리가 추가한 mass_to_flipper_length_ratio 속성을 사용해 계산을 수행할 거예요. 참고를 위해 WeightEntry dataclass를 다시 보여드립니다.

@dataclass
class WeightEntry:
    # Define the fields on the class
    species: str
    flipper_length: int
    body_mass: int
    sex: str

    @property
    def mass_to_flipper_length_ratio(self):
        return self.body_mass / self.flipper_length

이 연습은 강의의 일부입니다

Python의 데이터 타입

강의 보기

연습 안내

  • labeled_entries라는 이름의 빈 리스트를 만드세요.
  • 튜플 분해를 사용해 weight_log의 항목을 순회하며 species, flipper_length, body_mass, sex를 꺼내세요.
    • 각 항목마다 새로운 WeightEntry dataclass 인스턴스를 만들어 labeled_entries에 추가하세요.
  • 리스트 컴프리헨션을 사용해 처음 5개의 mass_to_flipper_length_ratio 값을 리스트로 만들어 출력하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# Create the empty list: labeled_entries
labeled_entries = []

# Iterate over the weight_log entries
for species, flipper_length, body_mass, ____ in weight_log:
    # Append a new WeightEntry instance to labeled_entries
    ____.____(____(species, flipper_length, body_mass, ____))
    
# Print a list of the first 5 mass_to_flipper_length_ratio values
print([____.____ for entry in labeled_entries[____]])
코드 편집 및 실행