def flatten(data):
output = []
for item in data:
if type(item) == list:
output += item
else:
output.append(item)
return output
def flatten2(data):
output=[]
for item in data:
if type(item) == list:
output +=flatten2(item)
else:
output.append(item)
return output
example = [[1,2,3],[4,[5,6]],[7,[8,9]]]
print("origin : ",example)
print("flattened : ",flatten(example))
print("flattened2 : ",flatten2(example))
### Explanation of the Flatten Functions
This code snippet features two functions designed to flatten nested lists in Python, but each with a different level of flattening capability. Let's dive into the details:
#### The `flatten` Function
- **Purpose**: To flatten a list one level deep. This means it only removes one layer of nesting in the list.
- **Mechanism**: It iterates through each item in the provided list (`data`). If an item is a list, it extends the `output` list by adding elements of this sublist directly. If the item is not a list, it appends the item to the `output` list.
#### The `flatten2` Function
- **Purpose**: To recursively flatten a list to all levels, removing all nesting.
- **Mechanism**: Similar to `flatten`, but when it encounters a list, it recursively calls itself (`flatten2`) to flatten the sublist. This approach ensures that all nested lists, no matter how deeply they are nested, get flattened.
#### Example and Output Analysis
- **`example = [[1,2,3],[4,[5,6]],[7,[8,9]]]`**: Defines a nested list with two levels of nesting in some parts.
- **`flatten(example)`** Output: `[1, 2, 3, 4, [5, 6], 7, [8, 9]]`. This demonstrates the one-level flattening capability of `flatten`. It does not flatten the nested lists `[5, 6]` and `[8, 9]`.
- **`flatten2(example)`** Output: `[1, 2, 3, 4, 5, 6, 7, 8, 9]`. This showcases the recursive flattening capability of `flatten2`, which removes all levels of nesting.
### Conclusion
- **Use `flatten`** when you need to reduce the nesting of a list by one level.
- **Use `flatten2`** for comprehensive flattening, eliminating all nesting within a list, no matter how deep.
'개념 > 혼자 공부하는 파이썬' 카테고리의 다른 글
python) Explanation of the Improved Student Management Code (3) | 2024.11.06 |
---|---|
python) datetime package (1) | 2024.11.05 |
python) Memoization (0) | 2024.11.03 |
python) Understanding Custom Exception Handling in Python (0) | 2024.11.02 |
python) custom exception class (2) | 2024.11.01 |