Home > Net >  Is there a way to use list comprehension on a single list containing different types of nested lists
Is there a way to use list comprehension on a single list containing different types of nested lists

Time:10-06

I understand nested list comprehension, but searched to see if it were possible to use nested list comprehension to separate the list in individual items on something like this: list1 = [ [1,2,3], [10,11,12], [100,111,112], [1, 10, 11, [1000101]]] I have not found anything online about it.

This was my idea:

def foo(x):
    for a in x:
        for b in a:
            if type(b) != list:
                unpacked = [b for a in x for b in a]
            if type(b) == list:
                unpacked.append(*b)

    return unpacked

However, the output is this: [1, 2, 3, 10, 11, 12, 100, 111, 112, 1, 10, 11, [1000101], 1000101]

CodePudding user response:

something like this?

    def foo(x):
        unpacked = []
        for a in x:
            unpacked.extend(
                [b for b in a]
            )
        return unpacked
    list1 = [ [1,2,3], [10,11,12], [100,111,112], [1, 10, 11, [1000101]]]
    print(foo(list1))

CodePudding user response:

Try this:

def unpacklist(list):
    alist = []
    a = 0
    for sublist in list:
        try:
            for i in sublist:
                alist.append(i)
        except TypeError:
            alist.append(sublist)
    for i in alist:
        if type(i) == type([]):
            a  = 1
            break
    if a == 1:
        return unpacklist(alist)
    if a == 0:
        return alist

list = [ [1,2,3], [10,11,12], [100,111,112], [1, 10, 11, [1000101]]]

a = unpacklist(list)

print(a)
  • Related