python-用numpy函数(例如numpy.where)替换多个if elif语句和条件

时间:2018-11-10 21:37:39

标签: python numpy if-statement

Radio_index,n_x和n_y是整数 我写了一个可以运行的if / elif代码。 目的是找到radio_index的x,y位置 我可以使用np.where

def radio_index2xy(radio_index,n_x,n_y): 

    con1 = radio_index <= n_x
    con2 = (radio_index > n_x) & (radio_index <= n_x+n_y-1)
    con3 = (radio_index > n_x+n_y-1) & (radio_index <= 2*n_x+n_y-2)
    con4 = (radio_index > 2*n_x+n_y-2) & (radio_index <= 2*n_x+2*n_y-4)
    condlist = [[con1],[con2],[con3],[con4]]
    choicelist = [[x_pos = radio_index -1 ,y_pos = 0],\
                  [(x_pos = n_x -1),(y_pos = radio_index - n_x)],\
                  [(x_pos = (n_x-1)-(radio_index-n_x-n_y+1)),(y_pos = n_y -1)],\
                  [(x_pos = 0),(y_pos = 2*n_x+2*n_y-4-radio_index+1)]]
    np.select(condlist,choicelist)

    return x_pos,y_pos 





if radio_index <= n_x:
    x_pos = radio_index -1
    y_pos = 0
elif radio_index > n_x and radio_index <= n_x+n_y-1:
    x_pos = n_x -1
    y_pos = radio_index - n_x
elif radio_index > n_x+n_y-1 and radio_index <= 2*n_x+n_y-2:
    x_pos = (n_x-1)-(radio_index-n_x-n_y+1)
    y_pos = n_y -1
elif radio_index > 2*n_x+n_y-2 and radio_index <= 2*n_x+2*n_y-4:
    x_pos = 0
    y_pos = 2*n_x+2*n_y-4-radio_index+1

1 个答案:

答案 0 :(得分:0)

np.searchsorted对于这种逻辑很有用:

def radio_index2xy_v(radio_index, n_x, n_y):
    sgn = np.array([0, 1, 1, -1, -1, 0])
    col = np.array([-1, 1, 0, 1, 0, -1])
    coeffs = np.array([[-1, -1],
                       [0, -1],
                       [-n_x, n_x - 1],
                       [n_y - 1, 2*n_x + n_y - 2],
                       [2*n_x + 2*n_y - 3, 0],
                       [-1, -1]])
    cusps = np.cumsum([0, n_x, n_y-1, n_x-1, n_y-2])
    idx = cusps.searchsorted(radio_index)
    out = coeffs[idx]
    out[np.arange(idx.size), col[idx]] += sgn[idx] * radio_index
    return out

演示:

>>> radio_index2xy_v(np.arange(20), 5, 4)
array([[-1, -1],
       [ 0,  0],
       [ 0,  1],
       [ 0,  2],
       [ 0,  3],
       [ 0,  4],
       [ 1,  4],
       [ 2,  4],
       [ 3,  4],
       [ 3,  3],
       [ 3,  2],
       [ 3,  1],
       [ 3,  0],
       [ 2,  0],
       [ 1,  0],
       [-1, -1],
       [-1, -1],
       [-1, -1],
       [-1, -1],
       [-1, -1]])