为了账号安全,请及时绑定邮箱和手机立即绑定

python - 用 numpy 函数(如 numpy.where)替换多个 if elif

python - 用 numpy 函数(如 numpy.where)替换多个 if elif

湖上湖 2021-08-14 16:25:29
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 = 0elif radio_index > n_x and radio_index <= n_x+n_y-1:    x_pos = n_x -1    y_pos = radio_index - n_xelif 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 -1elif 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 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

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]])


查看完整回答
反对 回复 2021-08-14
  • 1 回答
  • 0 关注
  • 326 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号