title: Interleave two numpy arrays based on element distances (python)
body: <p>I have two arrays, which can look like this:</p>
  
  <pre><code>X = np.array([ 157,  262,  368,  472,  577,  682,  786,  891,  996, 1100, 1204,
         1310, 1415, 1520, 1625, 1731, 1879])
  
  Y = np.array([  30,  135,  240,  345,  450,  555,  660,  765,  870,  975, 1080,
         1185, 1290, 1395, 1500, 1605])
  </code></pre>
  
  <p>The arrays will:</p>
  
  <ul>
  <li>Have values sorted in ascending order from start.</li>
  <li>Be of unequal length at times.</li>
  </ul>
  
  <p>I want to interleave these two into a new array <code>Z</code> based on the following:</p>
  
  <ul>
  <li>Each element may only be used once</li>
  <li>All elements need not be used</li>
  <li>An element <code>Xi</code> may only be included in <code>Z</code> if there is an element <code>Yj</code> in <code>Y</code> such that there are no other elements in <code>Y</code> with value difference smaller than <code>abs(Xi - Yj)</code> and that there are no element in <code>X</code> for which the value distance to <code>Yj</code> is smaller than <code>abs(Xi - Yj)</code>. (The same rule applies to elements in <code>Y</code>.)</li>
  </ul>
  
  <p>I see that I can do this with a bunch of nested for loops, but I wonder if there is some smarter, neater way of doing this?</p>
  
  <p>(I realize, the way I put the question, that it sounds like cut from a textbook. It is not. But maybe it is a classic sort function, who knows, but for me as a biologist... all I can say is I'm at a loss as how to solve it in an efficient, neat way.)</p>
  
  <p><strong>Edit: Not so pretty example</strong></p>
  
  <pre><code>new_list = list()
  for i in X:
      delta_i = np.abs(Y - i)
      delta_reciprocal = np.abs(X - Y[delta_i.argmin()])
      if delta_i.min() == delta_reciprocal.min():
          new_list += sorted([Y[delta_i.argmin()],
          X[delta_reciprocal.argmin()]])
  Z = np.array(new_list)
  </code></pre>
  
  <p>I'm not even totally sure it fulfills all the criteria, but when rewriting the old code I got down to just one loop... still there must be some nicer way!</p>