How to flatten a hetrogenous list of list into a single list in python?

前端 未结 11 1698
暖寄归人
暖寄归人 2020-12-01 22:59

I have a list of objects where objects can be lists or scalars. I want an flattened list with only scalars. Eg:

L = [35,53,[525,6743],64,63,[743,754,757]]
ou         


        
相关标签:
11条回答
  • 2020-12-01 23:17
    >>> data = [35,53,[525,6743],64,63,[743,754,757]]
    >>> def flatten(L):
            for item in L:
                if isinstance(item,list):
                    for subitem in item:
                        yield subitem
                else:
                    yield item
    
    
    >>> list(flatten(data))
    [35, 53, 525, 6743, 64, 63, 743, 754, 757]
    

    Here is a one-liner version for code-golf purposes (it doesn't look good :D )

    >>> [y for x in data for y in (x if isinstance(x,list) else [x])]
    [35, 53, 525, 6743, 64, 63, 743, 754, 757]
    
    0 讨论(0)
  • 2020-12-01 23:21
    def nchain(iterable):
        for elem in iterable:
            if type(elem) is list:
                for elem2 in elem:
                    yield elem2
            else:
                yield elem
    
    0 讨论(0)
  • 2020-12-01 23:21

    Recursive function that will allow for infinite tree depth:

    def flatten(l):
        if isinstance(l,(list,tuple)):
            if len(l):
                return flatten(l[0]) + flatten(l[1:])
            return []
        else:
            return [l]
    
    >>>flatten([35,53,[525,[1,2],6743],64,63,[743,754,757]])
    [35, 53, 525, 1, 2, 6743, 64, 63, 743, 754, 757]
    

    I tried to avoid isinstance so as to allow for generic types, but old version would infinite loop on strings. Now it flattens strings correctly (Not by characters now, but as if it's pretending a string is a scalar).

    0 讨论(0)
  • 2020-12-01 23:28
    outputList = []
    for e in l:
        if type(e) == list:
            outputList += e
        else:
            outputList.append(e)
    
    >>> outputList
    [35, 53, 525, 6743, 64, 63, 743, 754, 757]
    
    0 讨论(0)
  • 2020-12-01 23:31
    >>> L = [35,53,[525,6743],64,63,[743,754,757]]
    >>> K = []
    >>> [K.extend([i]) if type(i) == int else K.extend(i) for i in L ]
    [None, None, None, None, None, None]
    >>> K
    [35, 53, 525, 6743, 64, 63, 743, 754, 757]
    
    0 讨论(0)
提交回复
热议问题