중첩 리스트 평탄화

발행: (2025년 12월 8일 오후 07:55 GMT+9)
3 min read
원문: Dev.to

Source: Dev.to

Hey everyone! 👋
I know I’ve been a bit quiet lately. I actually came down with a pretty bad flu last week, which completely knocked me out. 🤒 That’s why I missed posting about the coding challenges. I’m finally feeling a bit better and ready to get back into the swing of things!

Problem Statement

목표는 다른 리스트를 포함할 수 있는(깊이에 관계없이 중첩된) 리스트를 받아서 하나의 1차원 리스트로 변환하는 함수를 작성하는 것입니다.

Examples

flatten([[1, 2], [3, 4], [5, 6]])  # → [1, 2, 3, 4, 5, 6]

flatten([1, [2, 3], [[4, 5], 6]])  # → [1, 2, 3, 4, 5, 6]

Solution

재귀를 이용한 파이썬 구현입니다. 재귀는 중첩 깊이가 얼마인지 모를 때 완벽하게 맞습니다!

def flatten(nested_list):
    """
    Flattens a nested list into a single-level list.
    """
    result = []
    for item in nested_list:
        if isinstance(item, list):
            flattened_sublist = flatten(item)  # Recursively flatten the sublist
            result.extend(flattened_sublist)
        else:
            result.append(item)
    return result

# Test cases
print(flatten([[1, 2], [3, 4], [5, 6]]))
# Output: [1, 2, 3, 4, 5, 6]

print(flatten([1, [2, 3], [[4, 5], 6]]))
# Output: [1, 2, 3, 4, 5, 6]

Explanation

  • Function definitiondef flatten(nested_list): 은 잠재적으로 중첩된 리스트를 인자로 받는 함수를 정의합니다.
  • Initialize resultresult = [] 은 평탄화된 요소들을 모을 빈 리스트를 생성합니다.
  • Iteratefor item in nested_list: 로 각 요소를 순회합니다.
  • Check for sublistif isinstance(item, list): 로 현재 요소가 리스트인지 확인합니다.
  • Recursive callflattened_sublist = flatten(item) 로 하위 리스트를 재귀적으로 평탄화합니다.
  • Extend resultresult.extend(flattened_sublist) 로 평탄화된 요소들을 메인 결과 리스트에 추가합니다.
  • Handle non‑list itemselse: result.append(item) 로 원자 요소를 직접 추가합니다.
  • Returnreturn result 로 완전히 평탄화된 리스트를 반환합니다.

이 함수의 아름다움은 유연성에 있습니다. 재귀 덕분에 2단계 중첩이든 200단계 중첩이든 같은 로직으로 처리할 수 있습니다!

Thanks for sticking with me while I recovered! I’ll be catching up on more challenges soon. Happy coding! 💻

Back to Blog

관련 글

더 보기 »

원숭이 시장

파트 1 또 다른 math gauntlet, 나는 여러 math operations를 프로그래밍하게 된다. 일부는 여러 conditionals의 일부가 될 것이다. 나는 이전에 해본 적이 있다. 나는 자신 있다.