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

前端 未结 11 1697
暖寄归人
暖寄归人 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:06

    Here is a relatively simple recursive version which will flatten any depth of list

    l = [35,53,[525,6743],64,63,[743,754,757]]
    
    def flatten(xs):
        result = []
        if isinstance(xs, (list, tuple)):
            for x in xs:
                result.extend(flatten(x))
        else:
            result.append(xs)
        return result
    
    print flatten(l)
    
    0 讨论(0)
  • 2020-12-01 23:09
    l = [35,53,[525,6743],64,63,[743,754,757]]
    outputList = []
    
    for i in l:
        if isinstance(i, list):
            outputList.extend(i)
        else:
            outputList.append(i)
    
    0 讨论(0)
  • 2020-12-01 23:13

    The answer is quite simple. Take advantage of recursion.

    def flatten(nst_lst, final_list):
    
        for val in nst_lst:
            if isinstance(val, list):
                flatten(val, final_list)
            else:
                final_list.append(val)
        return final_list
    
    #Sample usage
    fl_list = []
    lst_to_flatten = [["this",["a",["thing"],"a"],"is"],["a","easy"]]
    
    print(flatten(lst_to_flatten, fl_list))
    
    0 讨论(0)
  • 2020-12-01 23:14

    This solution is only for your specific situation (scalars within lists) and assumes the scalars are integer. It is a terrible solution but it is incredibly short.

    outputlist = map(int,",".split(str(L).replace("[","").replace("]","")))
    
    0 讨论(0)
  • 2020-12-01 23:15

    it could be done neatly in one line using numpy

    import numpy as np
    np.hstack(l)
    

    you end up with an ndarray

    array([  35,   53,  525, 6743,   64,   63,  743,  754,  757])
    
    0 讨论(0)
  • 2020-12-01 23:15

    Here's a oneliner, based on the question you've mentioned:

    list(itertools.chain(*((sl if isinstance(sl, list) else [sl]) for sl in l)))
    

    UPDATE: And a fully iterator-based version:

    from itertools import imap, chain
    list(chain.from_iterable(imap(lambda x: x if isinstance(x, list) else [x], l)))
    
    0 讨论(0)
提交回复
热议问题