Recursive processing of multi-layer nested list in Python (recommended)

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.