Python Chapter Seven After-Class Exercises (9)

Improve the function fun9, the parameter data is an integer list, insert two 8s between any two adjacent integers. Must use numpy. The return result is Numpy's ndarray type.

The idea of ​​this question is to create an np, the number is the number of two 8s inserted between the data data, and then all of them are made into 8, so the parameter in full is
len(data)+2*(len(data)- 1),8
Then use np slices not to copy, but to the characteristics of the view, just replace the element at a specific position with the data in data. The
idea is still quite clever

def fun9(data=[1,2,3,4,5]):
    """
    Arg:
        data : a list as input; e.g. [1,2,3,4,5]
    return a Numpy ndarray; e.g. [1 8 8 2 8 8 3 8 8 4 8 8 5]
    """
    
    nump=np.array(data)
    nplst=np.full(3*len(data)-2,8)
    nplst[::3]=nump
    return nplst

Guess you like

Origin blog.csdn.net/qq_53029299/article/details/115117637