杰瑞科技汇

Python array flatten有哪些方法?

Of course! In Python, the term "array" can be a bit ambiguous because there isn't a single built-in array type that's always used. People often mean a few different things:

Python array flatten有哪些方法?-图1
(图片来源网络,侵删)
  1. A standard Python list of lists. This is the most common scenario.
  2. A NumPy array. This is the standard for numerical computing in Python.
  3. The built-in array.array type, which is a more basic, C-style array.

The best way to "flatten" an array depends on which type you're using.

Let's cover the most common cases.


Flattening a List of Lists (The Pure Python Way)

This is the most frequent request. You have a list containing other lists, and you want to turn it into a single, flat list.

Method 1: Using itertools.chain (Most Efficient & Pythonic)

The itertools module is designed for efficient looping. itertools.chain() is perfect for this.

Python array flatten有哪些方法?-图2
(图片来源网络,侵删)
import itertools
list_of_lists = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# chain.from_iterable() takes an iterable of iterables (like a list of lists)
# and chains them together into a single iterator.
flattened = list(itertools.chain.from_iterable(list_of_lists))
print(flattened)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Method 2: List Comprehension (Concise & Readable)

This is a very popular and "Pythonic" way to flatten a list. It's less efficient for very large lists than itertools but is often preferred for its clarity.

list_of_lists = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# The inner loop iterates through each sublist (e.g., [1, 2, 3])
# The outer loop iterates through each item in the sublist (e.g., 1, then 2, then 3)
flattened = [item for sublist in list_of_lists for item in sublist]
print(flattened)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Note on the syntax: The order is important. It reads like a nested for-loop: for sublist in list_of_lists: -> for item in sublist:

Method 3: Using sum() (Simple but Inefficient)

This is a clever trick but is not recommended for large lists because it's very slow. It creates many intermediate lists in memory.

list_of_lists = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# The empty list [] is the starting point, and you add each sublist to it.
flattened = sum(list_of_lists, [])
print(flattened)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Flattening a NumPy Array

If you are working with numerical data, you are likely using NumPy. NumPy arrays have a built-in .flatten() method which is highly optimized.

Python array flatten有哪些方法?-图3
(图片来源网络,侵删)

First, make sure you have NumPy installed: pip install numpy

import numpy as np
# Create a 2D NumPy array
np_array = np.array([[1, 2, 3], [4, 5], [6, 7, 8, 9]])
# Note: The above will raise a ValueError because subarrays must have the same size.
# Let's create a proper rectangular array.
np_array_rect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Use the .flatten() method
flattened_np = np_array_rect.flatten()
print(flattened_np)
# Output: [1 2 3 4 5 6 7 8 9]
print(type(flattened_np))
# Output: <class 'numpy.ndarray'>
# If you need a standard Python list, convert it:
flattened_list = np_array_rect.flatten().tolist()
print(flattened_list)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(flattened_list))
# Output: <class 'list'>

Important NumPy Methods:

  • .flatten(): Returns a copy of the array. It's always safe to use because it doesn't modify the original array.
  • .ravel(): Returns a view of the array if possible. This is more memory-efficient as it doesn't create a new array. However, modifying the "flattened" array will modify the original. Use this when you are sure you don't need to keep the original array separate.
# Example of .ravel()
original = np.array([[1, 2], [3, 4]])
flattened_view = original.ravel()
print("Original:\n", original)
print("Flattened view:", flattened_view)
# Modifying the view also modifies the original array
flattened_view[0] = 99
print("\nAfter modifying the view:")
print("Original:\n", original) # Notice the original changed!
print("Flattened view:", flattened_view)

Flattening a Nested List of Arbitrary Depth

What if your list is nested more than one level deep? For example: [1, [2, [3, 4], 5]].

Here, recursion is a natural fit.

Method 1: Recursive Generator (Elegant & Memory-Efficient)

A generator is great because it produces items one by one without building the entire list in memory at once.

def flatten_recursive(nested_list):
    """Flattens a list of arbitrary depth."""
    for item in nested_list:
        if isinstance(item, list):
            # If the item is a list, recursively call the function
            yield from flatten_recursive(item)
        else:
            # If it's not a list, yield the item itself
            yield item
deeply_nested = [1, [2, [3, 4], 5], [6, 7], 8]
flattened_deep = list(flatten_recursive(deeply_nested))
print(flattened_deep)
# Output: [1, 2, 3, 4, 5, 6, 7, 8]

Method 2: Iterative Approach (Using a Stack)

This avoids recursion limits and can be more efficient for extremely deep structures.

def flatten_iterative(nested_list):
    """Flattens a list of arbitrary depth using a stack."""
    stack = list(nested_list) # Put all items on the stack
    result = []
    while stack:
        current = stack.pop()
        if isinstance(current, list):
            # If it's a list, extend the stack with its items
            # (Note: using extend reverses the order, so we can use reversed(current))
            stack.extend(reversed(current))
        else:
            result.append(current)
    # The result is built in reverse order, so we reverse it at the end
    return result[::-1]
deeply_nested = [1, [2, [3, 4], 5], [6, 7], 8]
flattened_deep = flatten_iterative(deeply_nested)
print(flattened_deep)
# Output: [1, 2, 3, 4, 5, 6, 7, 8]

Summary & Recommendation

Your Goal Recommended Method Why?
Simple 2D list of lists itertools.chain.from_iterable() Most memory-efficient and fastest for this common case. The "Pythonic" standard.
Simple 2D list of lists (alternative) List Comprehension Very readable and concise. A great choice for code clarity.
Working with NumPy arrays numpy_array.flatten() The idiomatic, built-in, and highly optimized way to handle NumPy arrays.
Flattening a list of arbitrary depth Recursive Generator (yield from) Elegant, memory-efficient, and easy to understand for the recursive problem.
Flattening a list of arbitrary depth (alt) Iterative approach (Stack) Avoids Python's recursion depth limits and can be faster for extremely deep structures.
分享:
扫描分享到社交APP
上一篇
下一篇