Python多層嵌套list的遞歸處理方法(推薦)
問題:用Python處理一個(gè)多層嵌套list
['and', 'B', ['not', 'A'],[1,2,1,[2,1],[1,1,[2,2,1]]], ['not', 'A', 'A'],['or', 'A', 'B' ,'A'] , 'B']
需求1)如何展開成一層?
需求2)如何刪除重復(fù)的元素? 包括重復(fù)的list, 要考慮子list的重復(fù)元素刪除后造成的子list重復(fù)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def unilist(ll):
"""
功能:用遞歸方法刪除多層列表中重復(fù)元素
"""
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 result
def flatten(ll):
"""
功能:用遞歸方法展開多層列表,以生成器方式輸出
"""
if isinstance(ll, list):
for i in ll:
for element in flatten(i):
yield element
else:
yield ll
testcase= ['and', 'B', ['not', 'A'],[1,2,1,[2,1],[1,1,[2,2,1]]], ['not', 'A', 'A'],['or', 'A', 'B' ,'A'] , 'B']
print unilist(testcase)
print list(flatten(testcase))
運(yùn)行結(jié)果
['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']
以上這篇Python多層嵌套list的遞歸處理方法(推薦)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python3查找列表中重復(fù)元素的個(gè)數(shù)的3種方法詳解
這篇文章主要介紹了Python3查找列表中重復(fù)元素的個(gè)數(shù)方法詳解,需要的朋友可以參考下2020-02-02
Python中的異常處理:try?except?Exception?as?e解決辦法
這篇文章主要介紹了Python中的異常處理機(jī)制,包括try、except、finally語句的基本用法和高級(jí)用法,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-04-04
numpy中的norm()函數(shù)求范數(shù)實(shí)例
這篇文章主要介紹了numpy中的norm()函數(shù)求范數(shù)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
Python2和Python3中@abstractmethod使用方法
這篇文章主要介紹了Python2和Python3中@abstractmethod使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
用sleep間隔進(jìn)行python反爬蟲的實(shí)例講解
在本篇文章里小編給大家整理了一篇關(guān)于用sleep間隔進(jìn)行python反爬蟲的實(shí)例講解內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。2020-11-11
Python使用QQ郵箱發(fā)送郵件實(shí)例與QQ郵箱設(shè)置詳解
這篇文章主要介紹了Python發(fā)送QQ郵件實(shí)例與QQ郵箱設(shè)置詳解,需要的朋友可以參考下2020-02-02

