Python Flatten Function: Usage & Examples

In Python, the flatten function is commonly used to flatten nested lists (or other iterable objects) into a one-dimensional list. This is very helpful when working with nested data structures, as it can simplify data processing and operations.

Here is an example showing how to write a flatten function:

def flatten(lst):
    flat_list = []
    for item in lst:
        if isinstance(item, list):
            flat_list.extend(flatten(item))
        else:
            flat_list.append(item)
    return flat_list

By using this flatten function, nested lists can be flattened into a one-dimensional list. For example:

nested_list = [1, [2, 3], [4, [5, 6]]]
flattened_list = flatten(nested_list)
print(flattened_list)
# 输出:[1, 2, 3, 4, 5, 6]

In this way, nested lists are flattened into a one-dimensional list. It is important to note that the flattening function will recursively handle nested lists until all levels of nesting are flattened into a one-dimensional list.

bannerAds