您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python多层嵌套list的递归处理方法(推荐)

5b51 2022/1/14 8:19:08 python 字数 3019 阅读 408 来源 www.jb51.cc/python

问题:用Python处理一个多层嵌套list [\'and\',\'B\',[\'not\',\'A\'],[1,2,1,[2,1],1]]],\'A\',[\'or\',\'B\']

概述

问题:用Python处理一个多层嵌套list

['and','B',['not','A'],[1,2,1,[2,1],1]]],'A',['or','B']

需求1)如何展开成一层?

需求2)如何删除重复的元素? 包括重复的list,要考虑子list的重复元素删除后造成的子list重复

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def unilist(ll):
  
  """
  功能:用递归方法删除多层列表中重复元素
  """
  
  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']

print unilist(testcase)

print list(flatten(testcase))

运行结果

['and','B']]

['and','not','or','B']

以上这篇Python多层嵌套list的递归处理方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。

总结

以上是编程之家为你收集整理的Python多层嵌套list的递归处理方法(推荐)全部内容,希望文章能够帮你解决Python多层嵌套list的递归处理方法(推荐)所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶