Flatten or group array in blocks of columns - NumPy / Python

前端 未结 6 678
醉酒成梦
醉酒成梦 2020-12-04 03:00

Is there any easy way to flatten

import numpy    
np.arange(12).reshape(3,4)
Out[]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11         


        
6条回答
  •  猫巷女王i
    2020-12-04 03:34

    I have a solution that doesn't involve numpy if you want, and it will take care for every kind of array you'll get,

    [[12312],[],[[]]] 
    [[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]
    [-1, [1, [-2], 1], -1]
    etc
    

    First option(won't work for strings)

    def flat_list(array):
        return list(flatten(array))              
    def flatten(nested): 
        try:
            for sublist in nested:
                for element in flatten(sublist):
                    yield element
        except TypeError:
            yield nested
    

    Second option:

    def flatten(nested): #in case you got strings and you want to avoide an infinite recursion
        try:
            # Don't iterate over string-like objects:
            try: nested + ''
            except TypeError: pass
            else: raise TypeError
            for sublist in nested:
                for element in flatten(sublist):
                    yield element
        except TypeError:
            yield nested
    

提交回复
热议问题