current position：Home>Python code reading (chapter 35): fully (deeply) expand nested lists
Python code reading (chapter 35): fully (deeply) expand nested lists
20220129 11:08:15 【FelixZ】
Python Code reading collection Introduction ： Why not recommend Python Beginners directly look at the project source code
The code read in this article realizes the complete expansion of all nesting levels of a nested list , The function of forming a simple list .
The code snippet read in this article comes from 30secondsofpython.
deep_flatten
from collections.abc import Iterable
def deep_flatten(lst):
return [a for i in lst for a in deep_flatten(i)] if isinstance(lst, Iterable) else [lst]
# EXAMPLES
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
Copy code
deep_flatten
The function receives a nested list , Return to the fully expanded list . Function USES isinstance()
And collections.abc.Iterable
To check whether an element is iteratable （ Is it list
）. If it is , Recursively call... In the list derivation deep_flatten()
function , Otherwise return to [lst]
.
Primitive function ：
def deep_flatten(lst):
return [a for i in lst for a in deep_flatten(i)] if isinstance(lst, Iterable) else [lst]
Copy code
It can be rewritten as ：
def deep_flatten(lst):
if isinstance(lst, Iterable):
return [a for i in lst for a in deep_flatten(i)]
else:
return [lst]
Copy code
Function judgment if lst
If it's an iteratable object , Is executed return [a for i in lst for a in deep_flatten(i)]
. At this moment if i
Is an iterable object , stay deep_flatten(i)
The list derivation will continue to be called in , Continue to expand the nested list ; If i
It's not an iterative object , In deep_flatten(i)
And you'll come back [i]
, here a
The value is i
, In the list derivation, you will get the element of a non iteratable object , Untie the nesting layer on the element .
A step closer , The function can be rewritten as ：
from collections.abc import Iterable
def deep_flatten(lst):
temp = []
def f(lst):
if isinstance(lst, Iterable):
for i in lst:
for a in f(i):
temp.append(a)
return []
else:
return [lst]
f(lst)
return temp
print(deep_flatten([1, [2], [[3], 4], 5])) # [1,2,3,4,5]
Copy code
copyright notice
author[FelixZ],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201291108133715.html
The sidebar is recommended
 [Python introduction project] use Python to generate QR code
 Quickly build Django blog based on function calculation
 Python collects and monitors system data  psutil
 Python interface test unittest usage details
 Implementation of toplevel design pattern in Python
 You can easily get started with Excel. Python data analysis package pandas (VII): breakdown
 Python simulation random coin toss (non optimized version)
 Using linear systems in python with scipy.linalg
 Using linear systems in python with scipy.linalg
 Together with Python to do a license plate automatic recognition system, fun and practical!
guess what you like

Using linear systems in python with scipy.linalg

Fast power modulus Python implementation of large numbers

Quickly build Django blog based on function calculation

You can easily get started with Excel pandas (I): filtering function

You can easily get started with Excel. Python data analysis package pandas (II): advanced filtering (I)

You can easily get started with Excel. Python data analysis package pandas (2): advanced filtering (2)

How does Python correctly call jar package encryption to get the encrypted value?

Python 3 interview question: give an array. If there is 0 in the array, add a 0 after 0, and the overall array length remains the same

Python simple Snake game (single player mode)

Using linear systems in python with scipy.linalg
Random recommended
 Python executes functions and even code through strings! Come and understand the operation of such a top!
 Decoding the verification code of Taobao slider with Python + selenium, the road of information security
 [Python introduction project] use Python to generate QR code
 Vanessa basks in her photos and gets caught up in the golden python. There are highlights in the accompanying text. She can't forget Kobe after all
 [windows] Python installation pyteseract
 [introduction to Python project] create bar chart animation in Python
 Python series tutorials 116
 Practical series 1 ️⃣ Wechat applet automatic testing practice (with Python source code)
 Python Basics: do you know how to use lists?
 Solution of no Python 3.9 installation was detected when uninstalling Python
 [common links of Python & Python]
 [Python development tool tkinterdiesigner]: example: develop stock monitoring alarm using Tkinter desinger
 [Python development tool Tkinter designer]: Lecture 1: introduction to the basic functions of Tkinter Designer
 [introduction to Python tutorial] use Python 3 to teach you how to extract any HTML main content
 Python socket implements UDP server and client
 Python socket implements TCP server and client
 leetcode 1974. Minimum Time to Type Word Using Special Typewriter（python）
 The mobile phone uses Python to operate picture files
 [learning notes] Python exception handling try except...
 Two methods of using pandas to read poorly structured excel. You're welcome to take them away
 Python sum (): the summation method of Python
 Practical experience sharing: use pyo3 to build your Python module
 Using Python to realize multitasking process