The following small series will bring you a Python multi-layer nested list recursive processing method (recommended ). I think this is quite good. now I will share it with you and give you a reference. Let's take a look at it with Xiaobian.
Problem: use Python to process a multi-layer nested list
['and', 'B', ['not', 'A'],[1,2,1,[2,1],[1,1,[2,2,1]]], ['not', 'A', 'A'],['or', 'A', 'B' ,'A'] , 'B']
Requirement 1)How to expand to a layer?
Requirement 2)How do I delete repeated elements? This includes duplicate lists. you must consider the duplicate sub-lists caused by the deletion of repeated sub-list elements.
#! /Usr/bin/env python #-*-coding: UTF-8-*-def unilist (ll): "" function: recursively delete the repeated element "result = [] for I in ll: if isinstance (I, list): if unilist (I) not in result: result. append (unilist (I) else: if I not in result: result. append (I) return resultdef flatten (ll): "" function: uses recursive methods to expand multi-layer lists and outputs "if isinstance (ll, list) as a generator ): for I in ll: for element in flatten (I): yield element else: yield lltestcase = ['and', 'B', ['not', 'A'], [, 1, [], [, [, 1], ['not', 'A', 'A'], ['or ', 'A', 'B', 'A'], 'B'] print unilist (testcase) print list (flatten (testcase ))
Running result
['and', 'B', ['not', 'A'], [1, 2, [2, 1], [1, [2, 1]]], ['or', 'A', 'B']]['and', 'B', 'not', 'A', 1, 2, 1, 2, 1, 1, 1, 2, 2, 1, 'not', 'A', 'A', 'or', 'A', 'B', 'A', 'B']
The recursive processing method (recommended) of the above multi-layer nested list in Python is all the content that I share with you. I hope you can give us a reference and support me a lot.