社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何清除无关嵌套中的python列表?

Vidur Gupta • 4 年前 • 773 次点击  

我正在开发一个程序,在这个程序中,我们有一个特定的列表,其中包含大量的无关嵌套,我们希望简化这些嵌套。

例如,一个输入可以是

[[['A', [[[[[[[[[['B', [[[[[[[[[['C', [[[[[[[[[['D']], [['E']], [['F', [[[[[[[[[['G']]]]]]]]]]]], [['H']], [['I']], [['J']]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

它应该输出 ['A', ['B', ['C', [['D'], ['E'], ['F', ['G']], ['H'], ['I'], ['J']]]]]

但是,在运行了我的代码之后,它没有做任何事情并返回 [] .

这是我的代码:

def clean_list(list2):
    for item in list2:
        if isinstance(item, list) and len(list2)==1: # this is an extraneous list!
            item = clean_list(item)
            list2.append(item[0].copy())
            list2.remove(item)
    return list2
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39379
 
773 次点击  
文章 [ 1 ]  |  最新文章 4 年前
blhsing
Reply   •   1 楼
blhsing    4 年前

您可以使用一个函数来递归地对给定列表中的每个项进行反嵌套,但如果列表只有一个项,并且该项是列表,则将子列表传递给递归调用:

def denest(lst):
    if isinstance(lst, list):
        if len(lst) == 1 and isinstance(lst[0], list):
            return denest(lst[0])
        return [denest(i) for i in lst]
    return lst

所以给出了存储在变量中的示例列表 lst , denest(lst) 将返回:

['A', ['B', ['C', [['D'], ['E'], ['F', ['G']], ['H'], ['I'], ['J']]]]]