脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python多层嵌套list的递归处理方法(推荐)

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

2020-08-26 09:46Python教程网 Python

下面小编就为大家带来一篇Python多层嵌套list的递归处理方法(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/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', ['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))

运行结果

?
1
2
3
['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的递归处理方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐