📅  最后修改于: 2023-12-03 15:18:55.303000             🧑  作者: Mango
Sometimes we work with arrays (lists) that contains arrays (lists). In order to make some manipulations or simply readability, we need to transform this array of arrays into a flat one. In this tutorial, we will learn different methods to flatten an array of arrays with Python.
We can iterate over each element of the outer array and, inside this loop, iterate over each element of the inner array. Then, we append each element to a new flat list.
def flatten(arr):
flat_arr = []
for sublist in arr:
for ele in sublist:
flat_arr.append(ele)
return flat_arr
We can use a nested list comprehension to flatten an array of arrays. In this method, we iterate over each element of each sublist, and append it to a new flat list.
def flatten(arr):
flat_arr = [ele for sublist in arr for ele in sublist]
return flat_arr
We can use the itertools.chain
function to chain all the sublists into one flat list.
import itertools
def flatten(arr):
flat_arr = list(itertools.chain.from_iterable(arr))
return flat_arr
We can define a recursive function that flattens any arbitrary nested list. In this function, we check if an element is a list. If it is, we call the function again passing this element as a parameter. If it is not, we append this element to a new flat list.
def flatten(arr):
flat_arr = []
for ele in arr:
if isinstance(ele, list):
flat_arr.extend(flatten(ele))
else:
flat_arr.append(ele)
return flat_arr
In this tutorial, we saw different methods to flatten an array of arrays with Python. Depending on the situation, we should choose the most efficient and readable method for our code.