More efficient way to write in Pytorch

Hello I am new in PyTorch, I was wondering what be a more efficient way to write this in Pytorch, possibly getting rid of the for loops or maybe the conditional statements

def fit_dz(z,v_pieces,w_pieces):
z,_=torch.sort(z)
g_dz=torch.zeros(z.shape,)
for i in range(len(z)):
for j in range(len(w_pieces)-1):
if 0 < z[i] < v_pieces[0]:
j=0
g_dz[i]= ((v_pieces[j]-0)/(w_pieces[j]-0))
elif v_pieces[j] < z[i] < v_pieces[j+1]:
g_dz[i]= ((v_pieces[j+1]-v_pieces[j])/(w_pieces[j+1]-w_pieces[j]))
return g_dz

z, v_pieces,w_pieces are just 1-d tensors.