중첩 리스트 평탄화
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 definition –
def flatten(nested_list):은 잠재적으로 중첩된 리스트를 인자로 받는 함수를 정의합니다. - Initialize result –
result = []은 평탄화된 요소들을 모을 빈 리스트를 생성합니다. - Iterate –
for item in nested_list:로 각 요소를 순회합니다. - Check for sublist –
if isinstance(item, list):로 현재 요소가 리스트인지 확인합니다. - Recursive call –
flattened_sublist = flatten(item)로 하위 리스트를 재귀적으로 평탄화합니다. - Extend result –
result.extend(flattened_sublist)로 평탄화된 요소들을 메인 결과 리스트에 추가합니다. - Handle non‑list items –
else: result.append(item)로 원자 요소를 직접 추가합니다. - Return –
return result로 완전히 평탄화된 리스트를 반환합니다.
이 함수의 아름다움은 유연성에 있습니다. 재귀 덕분에 2단계 중첩이든 200단계 중첩이든 같은 로직으로 처리할 수 있습니다!
Thanks for sticking with me while I recovered! I’ll be catching up on more challenges soon. Happy coding! 💻