简体   繁体   中英

Function with while loop no breaking

Here is the code:

def unnestList(l):
    result=[]
    for elem in l:
        while True:
            if not isinstance(elem,list):
                break
            else:
                for e in elem:
                    if isinstance(e,list):
                        elem = e[:]
                        continue
                    else:
                        break
        result.append(elem)
    return result

So I'm trying to unnest(sorry if it's not the correct word) a list of irregular lists. Sample input:

[['A','B'],[['A']]]
[[['A', 'B', 'C']], [[[['A', 'D', 'E', 'B', 'C']]]]]

Expected output:

[['A','B'],['A']]
[['A', 'B', 'C'],['A', 'D', 'E', 'B', 'C']]

Removing the while True loop seems to make it just fine.

def unnestList(l):
    result=[]
    for elem in l:
        if not isinstance(elem,list):
            break
        else:
            for e in elem:
                if isinstance(e,list):
                    elem = e[:]
                else:
                    break
        print(elem)
        result.append(elem)
    return result

在此处输入图像描述

Edit: seems like it still doesn't work for a nested list.

Second edit: Samwise helped you already:)

The while True loop doesn't have a terminating condition in all cases. Removing it completely (as in Kfir Ram's answer) seems to fix the problem for your sample inputs, but doesn't handle deeper nesting.

A recursive solution would be a little easier to follow IMO:

>>> def unnest_list(obj):
...     if not isinstance(obj, list):
...         return obj
...     if len(obj) == 1 and isinstance(obj[0], list):
...         return unnest_list(obj[0])
...     return [unnest_list(i) for i in obj]
...
>>> unnest_list([[[[[[['A']]]]]], [[[[[['B']]]]]]])
[['A'], ['B']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM